def updatePix(self, save):

        # print("update")
        outPixmap = QPixmap(self.inputFilePath + "/" + self.inputFileName)
        # print(self.inputFilePath)

        painter = QPainter(outPixmap)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setPen(QColor(255, 255, 255))

        for dict in self.currentMessagesDatas:
            msg = dict["linedit"].text()
            self.drawTextAlongCubic(dict["descriptor"], painter, "", msg)

        self.previewLabel.setPixmap(
            outPixmap.scaled(outPixmap.width() / 3,
                             outPixmap.height() / 3,
                             Qt.KeepAspectRatio,
                             transformMode=Qt.SmoothTransformation))

        if save == True:
            normPath = os.path.normpath(self.inputFilePath + "/" +
                                        self.inputFileName)
            file = QFile(normPath)
            file.open(QIODevice.WriteOnly)
            outPixmap.save(file, "PNG")

        del painter
Esempio n. 2
0
def take_screenshot(window, screenshots_dir):
    timestamp = int(time.time())
    pixmap = QPixmap(window.rect().size())
    window.render(pixmap, QPoint(), QRegion(window.rect()))
    screenshots_dir.mkdir(exist_ok=True)
    img_name = 'exception_screenshot_%d.jpg' % timestamp
    pixmap.save(str(screenshots_dir / img_name))
Esempio n. 3
0
 def store_file(self, id, file):
     id = id.replace('/', '_')
     directory = ApplicationData.get('images')
     filename = os.path.join(directory, id + '.png')
     if filename == os.path.normpath(file):
         return self.iconmap.get(id, None)
     makedirs(directory)
     pixmap = QPixmap()
     if file is not None and pixmap.load(file):
         if pixmap.size().width() > self.max_size or pixmap.size().height() > self.max_size:
             pixmap = pixmap.scaled(self.max_size, self.max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
         buffer = QBuffer()
         pixmap.save(buffer, 'png')
         data = str(buffer.data())
         with open(filename, 'wb') as f:
             f.write(data)
         icon = QIcon(pixmap)
         icon.filename = filename
         icon.content = data
         icon.content_type = 'image/png'
     else:
         unlink(filename)
         icon = None
     self.iconmap[id] = icon
     return icon
Esempio n. 4
0
 def setHead(self, qq, name, head):
     """设置头像"""
     self.blog_head_label.setToolTip(name)
     pixmap = QPixmap()
     pixmap.loadFromData(head)
     path = os.path.join(Settings().dataDir, "images", "head.png")  # 头像保存路径
     pixmap.save(path, format="png")
     if os.path.exists(path):  # 如果存在
         # 匹配出样式
         qss = re.findall("#blog_head_label(.*?)}", self.styleSheet(), re.S)
         if qss:
             # 修改头像的样式
             qss = "#blog_head_label" + re.sub(
                 "url\((.*?)\)", "url(%s/images/head.png)" %
                 Settings().dataDir, qss[0]) + "}"
             self.blog_head_label.setStyleSheet(qss)
             return
     # 不存在则直接处理
     # ---变成圆形---
     pixmap = self.getRoundPixmap(pixmap)
     #-------------
     # 调整大小
     pixmap = pixmap.scaled(self.blog_head_label.size())
     self.blog_head_label.setIcon(QIcon(pixmap))
     self.blog_head_label.setIconSize(self.blog_head_label.size())
Esempio n. 5
0
 def saveFunction(self, crop):
     if self.crop is not None:
         crop = QPixmap(self.convertToQimage(self.crop))
         file_path, _ = QFileDialog.getSaveFileName(self, 'Save as image',
                                                    '', '*.png')
         if file_path:
             crop.save(file_path)
Esempio n. 6
0
def export_tv_graph(graph_filename, scene):

    # define the bounding rectangle for pixmap for painter to paint in
    w = int(scene.width()) + 40
    h = int(scene.height()) + 40
    pixmap = QPixmap(w, h)
    painter = QPainter(pixmap)
    painter.fillRect(0,0,w,h, QColor("#f0f0f0"))

    # get a default option object.  It is neither a QStyleOptionViewItem
    # nor a QStyleOptionGraphicsItem and we don't use it, but we need something.
    option = QStyleOptionViewItem()

    # paint the annotation, texture graphs, and similarity lines
    painter.translate(20,12)
    scene.tv_g_annotation.paint(painter, option, None)
    painter.translate(0,scene.tv_g_annotation.boundingRect().height()+35)
    scene.tv_g_texture1.paint(painter, option, None)
    painter.translate(0,100)
    scene.tv_g_lines.paint(painter, option, None)
    painter.translate(0,200)
    scene.tv_g_texture2.paint(painter, option, None)
    painter.translate(0,140)
    scene.tv_g_histogram.paint(painter, option, None)
    painter.end()

    # export
    try:
        pixmap.save(graph_filename)

    except Exception as e:
        status = "Error exporting TV graph image file '%s': %s" % (
                                         graph_filename, str(e))
Esempio n. 7
0
 def __cssLinkClass(self, icon, size=32):
     """
     Private method to generate a link class with an icon.
     
     @param icon icon to be included (QIcon)
     @param size size of the icon to be generated (integer)
     @return CSS class string (string)
     """
     cssString = \
         """a.{{0}} {{{{\n"""\
         """  padding-left: {0}px;\n"""\
         """  background: transparent url(data:image/png;base64,{1})"""\
         """ no-repeat center left;\n"""\
         """  font-weight: bold;\n"""\
         """}}}}\n"""
     pixmap = icon.pixmap(size, size)
     imageBuffer = QBuffer()
     imageBuffer.open(QIODevice.ReadWrite)
     if not pixmap.save(imageBuffer, "PNG"):
         # write a blank pixmap on error
         pixmap = QPixmap(size, size)
         pixmap.fill(Qt.transparent)
         imageBuffer.buffer().clear()
         pixmap.save(imageBuffer, "PNG")
     return cssString.format(
         size + 4, str(imageBuffer.buffer().toBase64(), encoding="ascii"))
Esempio n. 8
0
 def __cssLinkClass(self, icon, size=32):
     """
     Private method to generate a link class with an icon.
     
     @param icon icon to be included (QIcon)
     @param size size of the icon to be generated (integer)
     @return CSS class string (string)
     """
     cssString = \
         """a.{{0}} {{{{\n"""\
         """  padding-left: {0}px;\n"""\
         """  background: transparent url(data:image/png;base64,{1})"""\
         """ no-repeat center left;\n"""\
         """  font-weight: bold;\n"""\
         """}}}}\n"""
     pixmap = icon.pixmap(size, size)
     imageBuffer = QBuffer()
     imageBuffer.open(QIODevice.ReadWrite)
     if not pixmap.save(imageBuffer, "PNG"):
         # write a blank pixmap on error
         pixmap = QPixmap(size, size)
         pixmap.fill(Qt.transparent)
         imageBuffer.buffer().clear()
         pixmap.save(imageBuffer, "PNG")
     return cssString.format(
         size + 4,
         str(imageBuffer.buffer().toBase64(), encoding="ascii"))
Esempio n. 9
0
def imageReceivedFromCamera(fileName, imageTempDir):
    modelName = myWindowUi.label_16.text()
    if fileName == 'noFile':
        myWindowUi.label_13.setText("카메라에서 저장된 파일이 없습니다.")
    elif fileName == 'noImg':
        myWindowUi.label_13.setText("해당폴더의 저장된 파일의 형식이 bmp 가 아닙니다.")
        os.remove(fileName)
    else:
        pixmap = QPixmap(fileName)
        pixmap_re = pixmap.scaled(190, 190, QtCore.Qt.KeepAspectRatio)
        myWindowUi.label_13.setPixmap(pixmap_re)
        parentPath = os.path.abspath(
            os.path.join(os.path.dirname(__file__), ".."))
        savingDir = os.path.join(parentPath, 'Imagelog', modelName)
        makeDirectory(savingDir)
        now = datetime.datetime.now()
        fileDir = savingDir + '/' + str(
            datetime.datetime.today().strftime("%Y%m%d_%H%M%S")) + '.bmp'
        print(fileDir)
        pixmap.save(fileDir)

        filelist = [f for f in os.listdir(imageTempDir)]
        for file in filelist:
            deleteFilePath = os.path.join(imageTempDir, file)
            os.remove(deleteFilePath)
Esempio n. 10
0
 def save(self):
     image = QPixmap(viewport.size()).toImage()
     viewport.render(image)
     try:
         image.save(filename)
     except NameError:
         image.save('image.jpg')
Esempio n. 11
0
    def cadProduto(self):
        INSERI = CrudProduto()
        INSERI.id = self.tx_idProduto.text()
        INSERI.produto = self.tx_DescricaoProduto.text().upper()
        if self.lb_FotoProduto.pixmap():
            imagem = QPixmap(self.lb_FotoProduto.pixmap())
            data = QByteArray()
            buf = QBuffer(data)
            imagem.save(buf, 'PNG')
            INSERI.imagem = str(data.toBase64()).encode('utf8')[2:-1]
        else:
            INSERI.imagem = False

        INSERI.categoria = self.cb_CategoriaProduto.currentData()
        INSERI.marca = self.cb_MarcaProduto.currentData()
        INSERI.estoqueMinimo = self.tx_EstoqueMinimoProduto.text()
        INSERI.estoqueMaximo = self.tx_EstoqueMaximoProduto.text()
        INSERI.obsProduto = self.tx_ObsProduto.text()
        INSERI.valorCompra = self.tx_ValorCompraProduto.text().replace(",", ".")
        INSERI.valorUnitario = self.tx_ValorUnitarioProduto.text().replace(",", ".")
        INSERI.valorAtacado = self.tx_ValorAtacadoProduto.text().replace(",", ".")
        INSERI.qtdeAtacado = self.tx_MinimoAtacado.text()
        INSERI.inseriProduto()

        self.janelaProdutos()
Esempio n. 12
0
    async def loadImg(self, src, name):
        try:
            async with aiohttp.ClientSession() as session:
                async with session.get(src, headers=headers,
                                       timeout=60) as response:
                    if response.status == 200:
                        image_content = await response.read()
                    else:
                        raise aiohttp.ClientError()
        except Exception as e:
            print(e)
            return

        width = self.width
        height = self.height

        pic = QPixmap()
        pic.loadFromData(image_content)
        localSrc = cacheFolder + '/' + name
        pic.save(localSrc, 'jpg')
        pic = pic.scaled(width, height)

        self.src = localSrc

        # 上遮罩。
        if self.pixMask:
            mask = QPixmap()
            mask.load(self.pixMask)
            mask = mask.scaled(width, height)

            pic.setMask(mask.createHeuristicMask())

        self.setPixmap(pic)
Esempio n. 13
0
    def CadEmpresa(self):
        INSERI = CrudEmpresa()
        INSERI.id = self.tx_idEmpresa.text()
        INSERI.nomeFantasia = self.tx_NomeFantasia.text().upper()
        INSERI.razaoSocial = self.tx_RazaoSocial.text().upper()
        INSERI.cnpj = self.tx_Cnpj.text()
        INSERI.inscEstadual = self.tx_IE.text()
        INSERI.telefone = re.sub(
            '[^[0-9]', '', (self.tx_TelefoneEmpresa.text()))
        INSERI.email = self.tx_EmailEmpresa.text()
        INSERI.site = self.tx_SiteEmpresa.text()
        INSERI.obs = self.tx_ObsEmpresa.text().upper()
        INSERI.cep = re.sub('[^[0-9]', '', (self.tx_CepEmpresa.text()))
        INSERI.endereco = self.tx_Endereco.text().upper()
        INSERI.numero = self.tx_NumEmpresa.text()
        INSERI.bairro = self.tx_BairroEmpresa.text().upper()
        INSERI.cidade = self.tx_CidadeEmpresa.text().upper()
        INSERI.estado = self.tx_EstadoEmpresa.text().upper()
        INSERI.titulo = self.tx_Titulo.text()
        INSERI.subtitulo = self.tx_SubTitulo.text()

        if self.lb_LogoEmpresa.pixmap():
            image = QPixmap(self.lb_LogoEmpresa.pixmap())
            data = QByteArray()
            buf = QBuffer(data)
            image.save(buf, 'PNG')
            logo = str(data.toBase64()).encode('utf8')[2:-1]
            INSERI.logo = logo
        else:
            INSERI.logo = False

        INSERI.inseriEmpresa()
        self.lb_NomeFantasia.setText(self.tx_Titulo.text())
        self.lb_NomeFantasia2.setText(INSERI.subtitulo)
        self.setWindowTitle(INSERI.titulo + " " + INSERI.subtitulo)
Esempio n. 14
0
 def store_data(self, id, data):
     id = id.replace('/', '_')
     directory = ApplicationData.get('images')
     filename = os.path.join(directory, id + '.png')
     makedirs(directory)
     pixmap = QPixmap()
     if data is not None and pixmap.loadFromData(data):
         image_size = pixmap.size()
         if image_size.width() > self.max_size or image_size.height() > self.max_size:
             pixmap = pixmap.scaled(self.max_size, self.max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
         if imghdr.what(None, data) != 'png' or pixmap.size() != image_size:
             buffer = QBuffer()
             pixmap.save(buffer, 'png')
             data = str(buffer.data())
         with open(filename, 'wb') as f:
             f.write(data)
         icon = QIcon(pixmap)
         icon.filename = filename
         icon.content = data
         icon.content_type = 'image/png'
     else:
         unlink(filename)
         icon = None
     self.iconmap[id] = icon
     return icon
Esempio n. 15
0
    def on_image_captured(self, id, captured_image):
        # The image to be displayed on screen
        self.captured2pixmap = QPixmap()
        success = self.captured2pixmap.convertFromImage(captured_image)

        self.list_pic_stats()

        self.thumb_scaled = self.captured2pixmap.scaled(
            self.picframe_width, self.picframe_height, Qt.KeepAspectRatio)
        self.ui.ThumbnailView.setScaledContents(True)
        self.ui.ThumbnailView.setSizePolicy(QSizePolicy.Ignored,
                                            QSizePolicy.Ignored)
        self.ui.FilenameDisp.setText(self.capture_name)
        self.ui.ThumbnailView.setPixmap(self.thumb_scaled)

        # The image to be saved to file as TIF
        # First confirm that the destination folder exists, create if it doesn't.
        self.manage_daily_folder()
        self.capture_fullpath = self.outdirname + "/" + self.capture_name
        outimage = QPixmap()
        outimage.convertFromImage(captured_image)
        outfile = QFile(self.capture_fullpath)
        outfile.open(QIODevice.WriteOnly)
        outimage.save(outfile, "TIFF")
        outfile.close()
Esempio n. 16
0
    def dataInResult(self,
                     data,
                     widgets=None,
                     name='None',
                     index=0,
                     loop=None):
        """默认将请求完成的数据填入result."""
        if data.error() == QNetworkReply.NoError:
            # 为控件添加图片。
            datas = data.readAll()
            # 为控件添加图片。
            pic = QPixmap()
            pic.loadFromData(datas)
            pic.save("cache/{0}".format(name))

            if widgets:
                widgets[index].setStyleSheets(
                    "QLabel#picLabel{border-image: url(cache/%s)}" % (name))

                # self.result.append(datas)
        # 释放掉事件锁。
        if loop:
            loop.exit()

        # 发出保存完毕的信号。
        self.saveFinished.emit(name)
Esempio n. 17
0
 def store_file(self, id, file):
     id = id.replace('/', '_')
     directory = ApplicationData.get('images')
     filename = os.path.join(directory, id + '.png')
     if filename == os.path.normpath(file):
         return self.iconmap.get(id, None)
     makedirs(directory)
     pixmap = QPixmap()
     if file is not None and pixmap.load(file):
         if pixmap.size().width() > self.max_size or pixmap.size().height(
         ) > self.max_size:
             pixmap = pixmap.scaled(self.max_size, self.max_size,
                                    Qt.KeepAspectRatio,
                                    Qt.SmoothTransformation)
         buffer = QBuffer()
         pixmap.save(buffer, 'png')
         data = str(buffer.data())
         with open(filename, 'wb') as f:
             f.write(data.encode())
         icon = QIcon(pixmap)
         icon.filename = filename
         icon.content = data
         icon.content_type = 'image/png'
     else:
         unlink(filename)
         icon = None
     self.iconmap[id] = icon
     return icon
Esempio n. 18
0
 def store_data(self, id, data):
     id = id.replace('/', '_')
     directory = ApplicationData.get('images')
     filename = os.path.join(directory, id + '.png')
     makedirs(directory)
     pixmap = QPixmap()
     if data is not None and pixmap.loadFromData(data):
         image_size = pixmap.size()
         if image_size.width() > self.max_size or image_size.height(
         ) > self.max_size:
             pixmap = pixmap.scaled(self.max_size, self.max_size,
                                    Qt.KeepAspectRatio,
                                    Qt.SmoothTransformation)
         if imghdr.what(None, data) != 'png' or pixmap.size() != image_size:
             buffer = QBuffer()
             pixmap.save(buffer, 'png')
             data = str(buffer.data())
         with open(filename, 'wb') as f:
             f.write(data.encode())
         icon = QIcon(pixmap)
         icon.filename = filename
         icon.content = data
         icon.content_type = 'image/png'
     else:
         unlink(filename)
         icon = None
     self.iconmap[id] = icon
     return icon
Esempio n. 19
0
 def createBackground(self):
     """создание подложки"""
     pixmap = QPixmap(self._graph.size())
     self._graph.render(pixmap)
     pixmap.save('render.png')
     self.setStyleSheet("QFrame {background-image: url('render.png');}")
     self._graph.setVisible(False)
Esempio n. 20
0
def renderToPixmap( widget: QWidget, outputPath=None ):
    rectangle = widget.geometry()
    pixmap = QPixmap( rectangle.size() )
    widget.render( pixmap, QPoint(), QRegion(rectangle) )
    if outputPath is not None:
        pixmap.save( outputPath )
    return pixmap
Esempio n. 21
0
    def _thumbnail_fetched(self, item_key: str, body: api_models.Body):

        if not item_key:
            log.debug('Fetching thumbnail failed, no item_key')
            self._remove_watcher(item_key)
            self.thumbnailFetchFailed.emit(item_key)
            return

        if body is None or not hasattr(body, 'response'):
            log.debug('Fetching thumbnail failed, no body')
            self._remove_watcher(item_key)
            self.thumbnailFetchFailed.emit(item_key)
            return

        resp: ReqResponse = body.response
        # log.debug(requests_response_metadata(resp))

        if not resp.ok:
            log.debug('Fetching thumbnail failed')
            self._remove_watcher(item_key)
            self.thumbnailFetchFailed.emit(item_key)
            return

        if ('content-type' not in resp.headers
                or resp.headers['content-type'] != 'image/png'):
            log.debug('Fetching thumbnail failed, not image/png')
            self._remove_watcher(item_key)
            self.thumbnailFetchFailed.emit(item_key)
            return

        # Try to load image data into QPixmap
        image_data = resp.content  # consume response data

        qp = QPixmap()
        if not qp.loadFromData(image_data, 'PNG'):
            log.debug('Fetching thumbnail failed, could not load PNG data')
            self._remove_watcher(item_key)
            self.thumbnailFetchFailed.emit(item_key)
            return

        # Write .png image to cache directory
        item_path = os.path.join(self._cache_dir, f'{item_key}{THUMB_EXT}')

        if os.path.exists(item_path):
            os.remove(item_path)

        qp.save(item_path, 'PNG')

        if GEOREFERENCE_PNG:
            # noinspection PyBroadException
            try:
                self._georeference_thumbnail(item_key, item_path)
            except:
                # TODO: Figure out all possibly thrown exceptions
                pass

        self._remove_watcher(item_key)

        self.thumbnailAvailable.emit(item_key, item_path)
Esempio n. 22
0
class Canvas(QWidget):
    drawn = pyqtSignal()

    def __init__(self, parent=None):
        super(Canvas, self).__init__(parent)
        self.setWindowTitle("MathPix+ - 画板")
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setWindowState(Qt.WindowActive | Qt.WindowFullScreen)
        self.setWindowIcon(QIcon("favicon.ico"))
        self.setFixedSize(QApplication.desktop().screenGeometry().width(),
                          QApplication.desktop().screenGeometry().height())
        self.canvas = QPixmap(QApplication.desktop().screenGeometry().width(),
                              QApplication.desktop().screenGeometry().height())
        self.canvas.fill(Qt.white)
        self.penSize = 8
        self.pen = QPen(Qt.black, self.penSize, Qt.SolidLine, Qt.RoundCap,
                        Qt.RoundJoin)
        self.setCursor(Qt.CrossCursor)
        self.lastPoint = QPoint()
        self.endPoint = QPoint()

    def paintEvent(self, event):
        painter = QPainter(self.canvas)
        painter.setPen(self.pen)
        painter.setRenderHint(QPainter.HighQualityAntialiasing, True)
        painter.drawLine(self.lastPoint, self.endPoint)
        self.lastPoint = self.endPoint
        pix_painter = QPainter(self)
        pix_painter.drawPixmap(0, 0, self.canvas)

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.lastPoint = event.pos()
            self.endPoint = self.lastPoint

    def mouseMoveEvent(self, event):
        if event.buttons() and Qt.LeftButton:
            self.endPoint = event.pos()
            self.update()

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.endPoint = event.pos()
            self.update()

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Backspace:
            self.canvas.fill(Qt.white)
            self.update()
        elif event.key() == Qt.Key_Escape:
            self.canvas.fill(Qt.white)
            self.update()
            self.close()
        elif event.key() == Qt.Key_Return or Qt.Key_Enter:
            self.canvas.save("canvas.jpg", "JPG")
            self.canvas.fill(Qt.white)
            self.update()
            self.drawn.emit()
            self.close()
Esempio n. 23
0
 def getFullScreen(self, temp):
     pix = QPixmap(self.window.mainWidget.size())
     self.window.mainWidget.render(pix)
     image = pix.toImage()
     s = image.bits().asstring(image.width() * image.height() * 3)
     arr = np.fromstring(s, dtype='uint8').reshape((image.width(), image.height(), 3))
     pix.save(temp)
     return arr
Esempio n. 24
0
 def export_graph(self):
     print("must export graph")
     # self.openSaveDialog()
     # def export_graph_jpg(self, filepath=""):
     p = QPixmap()
     self.vc_graph_widget.render(p)
     p.save("screenshot.jpg", 'jpg')
     return
Esempio n. 25
0
 def renderToImage(self, size: QSize, path_to_file=None):
     """отрисовка содержимого компонента в рисунок и в файл"""
     self.setGeometry(0, 0, size.width(), size.height())
     pixmap = QPixmap(self.size())
     self.render(pixmap)
     if path_to_file:
         pixmap.save(path_to_file)
     return pixmap
Esempio n. 26
0
class Menu(QMainWindow):
    xc, yc = -1, -1
    xx, yy = -1, -1
    def __init__(self):
        super().__init__()
        self.drawing = False
        self.lastPoint = QPoint()
        self.image = QPixmap(1100, 1000)#("white.png")
        self.title = 'Fill'
        self.setGeometry(0, 0, 1200, 1200)
        self.resize(self.image.width(), self.image.height())
        self.initUI()
        self.show()
            
    def initUI(self):
        self.setWindowTitle(self.title)
        button = QPushButton('Clear', self)
        button.clicked.connect(self.on_click1)
        button1 = QPushButton('Go', self)
        button1.move(0,30)
        button1.clicked.connect(self.on_click2)
        
        
    def on_click1(self):
        self.image = QPixmap(1000, 1000)
        self.show()
        
    def on_click2(self):
        self.image.save("toalgo.png") 
        gbr = cv2.imread("toalgo.png")
        bground = cv2.imread("back.jpeg")
        drawarea(gbr, bground, self.xx, self.yy)
        cv2.imshow('[eq', gbr)
        
        
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawPixmap(self.rect(), self.image)

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.drawing = True
            self.lastPoint = event.pos()
        if event.button() == Qt.RightButton:
            self.yy = event.pos().y()
            self.xx = event.pos().x()
            
    def mouseMoveEvent(self, event):
        if event.buttons() and Qt.LeftButton and self.drawing:
            painter = QPainter(self.image)
            painter.setPen(QPen(Qt.white, 3, Qt.SolidLine))
            painter.drawLine(self.lastPoint, event.pos())
            self.lastPoint = event.pos()
            self.update()

    def mouseReleaseEvent(self, event):
        if event.button == Qt.LeftButton:
            self.drawing = False
Esempio n. 27
0
 def onScreenShotClick(self, ev):
     pixmap = QPixmap(self.widget.rect().width(),
                      self.widget.rect().height())
     painter = QPainter()
     painter.begin(pixmap)
     self.widget.render(painter, QPoint(), QRegion(self.widget.rect()))
     painter.end()
     pixmap.save("screen" +
                 str(datetime.datetime.now().strftime("%I_%M_%S")) + ".png")
Esempio n. 28
0
def saveOneTexture(bin, offset, palette):
	picture = QPixmap(32, 32)
	qp = QPainter()
	qp.begin(picture)

	drawTexture(data, offset, palette, 0, 0, qp)

	qp.end()
	picture.save('./textures/texture_{0:08X}.png'.format(offset))
Esempio n. 29
0
 def ScaleAndSavePixmap(self, path):
     filepath = Path(path)
     well = filepath.stem
     pixmap = QPixmap(str(filepath))
     pixmap = pixmap.scaled(self.dx, self.dy, QtCore.Qt.KeepAspectRatio,
                            QtCore.Qt.FastTransformation)
     path = self.resizedpath.joinpath("%s.jpg" % well)
     pixmap.save(str(path))
     return 1  #return 1 when done to increment counter
Esempio n. 30
0
 def save_canvas(self, path: str):
     painter = QPainter()
     pix = QPixmap(600, 600)
     pix.fill(QColor(255, 255, 255))
     painter.begin(pix)
     for item in self.item_dict:
         self.item_dict[item].paint(painter)
     painter.end()
     pix.save(path)
 def saveImageDialog(self):
     fileName, _ = QFileDialog.getSaveFileName(
         self, "Save As Image", "", "All Files (*);;JPG Files (*.jpg)")
     if fileName != '':
         img = QPixmap(self.canvas.size())
         painter = QPainter(img)
         self.canvas.paint(painter)
         painter.end()
         img.save(fileName)
Esempio n. 32
0
 def save_canvas(self, filename, w, h):
     painter = QPainter()
     pix = QPixmap(w, h)
     pix.fill(QColor(255, 255, 255))
     painter.begin(pix)
     for item in self.item_dict:
         self.item_dict[item].paint(painter, QStyleOptionGraphicsItem)
     painter.end()
     pix.save(filename)
Esempio n. 33
0
    def saveDataFile(self):
        fname = QFileDialog.getSaveFileName(self, 'Save file', filter='*.png')

        if fname[0]:
            central_widget = self.centralWidget()
            pixmap = QPixmap(central_widget.size())
            central_widget.render(pixmap)
            pixmap.save(fname[0])
            self.statusBar().showMessage('Image was saved successfully')
Esempio n. 34
0
 def toImage(self, location = None, bucket = None):
     png = '/home/ubuntu/Desktop/capture.png'
     if location:            
         png = location         
     print 'toImage:', location
     if not self.opengl:
         print 'no opengl'
         return
     try:
         os.makedirs(os.path.dirname(png))
     except:
         pass
     print 'IMAGE CAPTURE', png, self.opengl
     pixmap = QPixmap(self.opengl.size())
     self.opengl.render(pixmap)
     pixmap.save(png)
     return png        
Esempio n. 35
0
    def screenshot(self, widget, name=None):
        """
        Take a screenshot of the widget. You can optionally append a string to the name of the screenshot. The
        screenshot itself is saved as a JPEG file.
        """
        pixmap = QPixmap(widget.rect().size())
        widget.render(pixmap, QPoint(), QRegion(widget.rect()))

        self.screenshots_taken += 1
        img_name = 'screenshot_%d.jpg' % self.screenshots_taken
        if name is not None:
            img_name = 'screenshot_%s.jpg' % name

        screenshots_dir = os.path.join(os.path.dirname(TriblerGUI.__file__), 'screenshots')
        if not os.path.exists(screenshots_dir):
            os.mkdir(screenshots_dir)

        pixmap.save(os.path.join(screenshots_dir, img_name))
Esempio n. 36
0
    def parseKey(self, ref_key=None):
        ret = None
        table_name = "fllarge"
        if ref_key is not None:
            value = None
            from pineboolib.pncontrolsfactory import aqApp
            
            tmp_dir = aqApp.tmp_dir()
            img_file = "%s/%s.png" % (tmp_dir, ref_key)
            
            if not os.path.exists(img_file) and ref_key[0:3] == "RK@":
                if not aqApp.singleFLLarge():  # Si no es FLLarge modo único añadimos sufijo "_nombre" a fllarge
                    table_name += "_%s" % ref_key.split("@")[1]

                q = FLSqlQuery()
                # q.setForwardOnly(True)
                q.exec_("SELECT contenido FROM %s WHERE refkey='%s'" % (table_name, ref_key))
                if q.next():
                    value = cacheXPM(q.value(0))

                if value:
                    ret = img_file
                    pix = QPixmap(value)
                    if not pix.save(img_file):
                        self.logger.warning("%s:refkey2cache No se ha podido guardar la imagen %s" % (__name__, img_file))
                        ret = None
                    else:
                       ret = img_file
            elif ref_key.endswith(".xpm"):
                pix = QPixmap(ref_key)
                img_file = ref_key.replace(".xpm",".png")
                if not pix.save(img_file):
                    self.logger.warning("%s:refkey2cache No se ha podido guardar la imagen %s" % (__name__, img_file))
                    ret = None
                else:
                    ret = img_file
                
            else:

                ret = img_file

        return ret
Esempio n. 37
0
 def setHead(self, qq, name, head):
     """设置头像"""
     self.blog_head_label.setToolTip(name)
     pixmap = QPixmap()
     pixmap.loadFromData(head)
     path = os.path.join(Settings().dataDir, "images", "head.png")    # 头像保存路径
     pixmap.save(path, format = "png")
     if os.path.exists(path):    # 如果存在
         # 匹配出样式
         qss = re.findall("#blog_head_label(.*?)}", self.styleSheet(), re.S)
         if qss:
             # 修改头像的样式
             qss = "#blog_head_label" + re.sub("url\((.*?)\)", "url(%s/images/head.png)" % Settings().dataDir, qss[0]) + "}"
             self.blog_head_label.setStyleSheet(qss)
             return
     # 不存在则直接处理
     # ---变成圆形---
     pixmap = self.getRoundPixmap(pixmap)
     #-------------
     # 调整大小
     pixmap = pixmap.scaled(self.blog_head_label.size())
     self.blog_head_label.setIcon(QIcon(pixmap))
     self.blog_head_label.setIconSize(self.blog_head_label.size())
Esempio n. 38
0
class OCRTranslator(QDialog):
    def __init__(self, parent=None, f=Qt.Tool | Qt.FramelessWindowHint | Qt.X11BypassWindowManagerHint):
        super(OCRTranslator, self).__init__(parent, f)
        self.desktopGeometry = self.getDesktopGeometry()
        self.setGeometry(self.desktopGeometry)
        self.setStyleSheet("background-color: #FFF;")
        self.setModal(True)
        self.setWindowOpacity(0.4)
        self.setCursor(Qt.CrossCursor)
        self.rubberBand = Selector(QRubberBand.Rectangle, self)
        self.rubberBand.setWindowOpacity(0.7)
        self.start, self.end = QPoint(), QPoint()
        self.hasSelected = False
        self.screenshot = QPixmap()
        self.shotfilename = None
        self.info = InfoPanel(self)
        self.info.setFixedSize(QSize(450, 100))
        self.info.setGeometry(OCRTranslator.getDesktopGeometry().width() - 460, 0, 450, 100)
        self.info.show()

    def mousePressEvent(self, ev):
        if ev.button() == Qt.LeftButton:
            self.info.close()
            self.setCursor(Qt.CrossCursor)
            self.start = QPoint(ev.pos())
            self.rubberBand.setGeometry(QRect(self.start, QSize()))
            self.rubberBand.show()

    def mouseMoveEvent(self, ev):
        if not self.start.isNull():
            self.rubberBand.setGeometry(QRect(self.start, ev.pos()).normalized())
            self.hasSelected = True

    def mouseReleaseEvent(self, ev):
        if ev.button() == Qt.LeftButton and self.hasSelected:
            self.end = QPoint(ev.pos())
            self.setCursor(Qt.ArrowCursor)
            self.hasSelected = False

    def keyPressEvent(self, ev):
        if ev.key() == Qt.Key_Escape:
            self.close()
        elif ev.key() in [Qt.Key_Enter, Qt.Key_Return] and not self.start.isNull() and not self.end.isNull():
            self.hide()
            QTimer().singleShot(500, self.takeScreenshot)

    def takeScreenshot(self):
        x = self.desktopGeometry.x() + self.start.x()
        y = self.desktopGeometry.y() + self.start.y()
        w = self.end.x() - self.start.x()
        h = self.end.y() - self.start.y()
        self.screenshot = qApp.screens()[0].grabWindow(qApp.desktop().winId(), x, y, w, h)
        self.shotfilename = os.path.join(self.getFilePath(), "www", "temp", strftime('%Y%m%d-%H%M%S')) + ".png"
        self.screenshot.save(self.shotfilename, "PNG", 100)
        if not self.shotfilename is None and type(self.screenshot) is QPixmap:
            self.openTranslator()

    @staticmethod
    def getDesktopGeometry():
        totalWidth = 0
        maxHeight = 0
        minX = 0
        screens = (qApp.screens()[i] for i in range(qApp.desktop().screenCount()))
        rects = [screen.geometry() for screen in screens]
        for rect in rects:
            totalWidth += rect.width()
            if rect.x() < minX:
                minX = rect.x()
            if rect.height() > maxHeight:
                maxHeight = rect.height()
        return QRect(minX, 0, totalWidth, maxHeight)

    @staticmethod
    def getFilePath():
        if getattr(sys, 'frozen', False):
            return sys._MEIPASS
        return os.path.dirname(os.path.realpath(sys.argv[0]))

    def getAppFrameSize(self):
        viewWidth = self.screenshot.width() + 85
        if viewWidth < 600:
            viewWidth = 600
        viewHeight = self.screenshot.height() + 185
        if viewHeight < 550:
            viewHeight = 550
        return QSize(viewWidth, viewHeight)

    def webServer(self):
        if getattr(sys, 'frozen', False):
            os.chdir(sys._MEIPASS)  
            for r, d, f in os.walk(sys._MEIPASS):
                os.chmod(r, 0o755)
        else:
        	os.chdir(os.path.join(QFileInfo(__file__).absolutePath(), 'www'))
        httpd = HTTPServer((self.address, self.port), OCRHTTPHandler)
        httpd.serve_forever()

    def openTranslator(self):
        self.address = "127.0.0.1"
        self.port = randint(2000, 5000)
        self.t = Thread(target=self.webServer)
        self.t.daemon = True
        self.t.start()
        self.view = QWebEngineView()
        self.view.setWindowTitle("OCR Translator")
        self.view.setWindowIcon(QIcon(os.path.join(self.getFilePath(), "www", "img", "app-icon.png")))
        self.view.setContextMenuPolicy(Qt.NoContextMenu)
        qryparam = urlencode({'img': self.shotfilename.split('\\').pop().split('/').pop()})
        self.url = QUrl("http://" + self.address + ":" + str(self.port) + "/index.html#?" + qryparam)
        self.view.load(self.url)
        self.view.setMinimumSize(self.getAppFrameSize())
        self.view.closeEvent = self.closeEvent
        self.view.show()

    def closeEvent(self, ev):
        qApp.quit()
Esempio n. 39
0
 def save_capture(self, filename):
     """Saves the current capture and its annotations to the given file."""
     pixmap = QPixmap(self.window.center_view.size())
     self.window.center_view.render(pixmap)
     pixmap.save(filename)
Esempio n. 40
0
class GameField:
    def __init__(self, size, scene: QGraphicsScene):
        self.rectItems = []
        self.pixmap = QPixmap(QSize(820,820))
        self.painter = QPainter(self.pixmap)
        self.scene = scene
        self.owners = None
        self.values = None
        pen = QPen()
        pen.setStyle(Qt.NoPen)
        for index in range(size**2):
            item = QGraphicsRectItem()
            item.setRect(int(index/size), int(index%size), 0.9, 0.9)
            item.setPen(pen)
            scene.addItem(item)
            self.rectItems.append(item)

    @pyqtSlot(int, np.ndarray, np.ndarray)
    def update(self, size, owners, values):
        own = list(np.unique(owners))[1:]
        noBrush = QBrush(Qt.NoBrush)
        first = False
        if self.owners is None or self.values is None:
            first = True
            self.owners = owners
            self.values = values
        for index, owner, value, cur_owner, cur_value in zip(range(size**2), owners.flat, values.flat, self.owners.flat, self.values.flat):
            if first or (cur_owner != owner or cur_value != value):
                if owner == 0:
                    brush = noBrush
                else:
                    k = colors[own.index(owner)]
                    color = QtGui.QColor(k[0], k[1], k[2], int(255./np.max(values)*value) if owner >= 1000 else 255)
                    brush = QBrush(color)
                item = self.rectItems[index]
                item.setBrush(brush)
        self.owners = owners
        self.values = values
        self.scene.update(self.scene.sceneRect())

    def outputPng(self):
        view = scene.views()[0]
        self.pixmap.fill(Qt.white)
        self.painter.setBackground(Qt.white)
        self.painter.setRenderHints(QtGui.QPainter.HighQualityAntialiasing)
        scene.render(self.painter, QRectF(10,10,800,800), QRectF(0,0,size,size))
        self.pixmap.save("out/state.png")

    def outputScorePage(self, owners, values, names, ids):
        with open('out/index.html', 'w') as f:
            f.write("""<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n
                <html>\n
                \t<head>\n
                \t\t<title>GPN16: Blobs</title>\n
                \t\t<style>\n
                \t\t\ttable\n
                \t\t\t{\n
                \t\t\t\tborder-collapse:collapse;\n
                \t\t\t\twidth:100%;\n
                \t\t\t}\n
                \t\t\tth,td\n
                \t\t\t{\n
                \t\t\t\ttext-align:left;\n
                \t\t\t\tpadding:8px;\n
                \t\t\t}\n
                \t\t\ttr:nth-child(even)\n
                \t\t\t{\n
                \t\t\t\tbackground-color:#f2f2f2;\n
                \t\t\t}\n
                \t\t\tth\n
                \t\t\t{\n
                \t\t\t\tbackground-color:#600000;\n
                \t\t\t\tcolor:white\n
                \t\t\t}\n
                \t\t</style>\n
                \t</head>\n
                \t<body>\n
                \t\t<h2><a href=\"http://www.gulas.ch\">GPN16</a>: <a href=\"http://www.github.com/scummos/blobs\">Blobs</a>$ Lobby</h2>\n
                \t\t<center>\n
                \t\t\t<img src=logo.svg /><br />\n
                \t\t\t<img src=state.png /><br />\n
                \t\t</center>\n
                \t\t<table>\n
                \t\t\t<tr>\n
                \t\t\t\t<th>Rank</th>\n
                \t\t\t\t<th>Bot name</th>\n
                \t\t\t\t<th>Score</th>\n
                \t\t\t</tr>\n""");
            #TODO: output ramsh here
            f.write("""\t\t</table>\n
                \t</body>\n
                </html>\n""")
            f.close()
Esempio n. 41
0
class SnapWidget(QWidget, Ui_SnapWidget):
    """
    Class implementing the snapshot widget.
    """
    ModeFullscreen = 0
    ModeScreen = 1
    ModeRectangle = 2
    ModeFreehand = 3
    ModeEllipse = 4
    
    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent reference to the parent widget (QWidget)
        """
        super(SnapWidget, self).__init__(parent)
        self.setupUi(self)
        
        self.saveButton.setIcon(UI.PixmapCache.getIcon("fileSaveAs.png"))
        self.takeButton.setIcon(UI.PixmapCache.getIcon("cameraPhoto.png"))
        self.copyButton.setIcon(UI.PixmapCache.getIcon("editCopy.png"))
        self.copyPreviewButton.setIcon(UI.PixmapCache.getIcon("editCopy.png"))
        self.setWindowIcon(UI.PixmapCache.getIcon("ericSnap.png"))
        
        self.modeCombo.addItem(self.tr("Fullscreen"),
                               SnapWidget.ModeFullscreen)
        self.modeCombo.addItem(self.tr("Rectangular Selection"),
                               SnapWidget.ModeRectangle)
        self.modeCombo.addItem(self.tr("Ellipical Selection"),
                               SnapWidget.ModeEllipse)
        self.modeCombo.addItem(self.tr("Freehand Selection"),
                               SnapWidget.ModeFreehand)
        if QApplication.desktop().screenCount() > 1:
            self.modeCombo.addItem(self.tr("Current Screen"),
                                   SnapWidget.ModeScreen)
        self.__mode = int(Preferences.Prefs.settings.value("Snapshot/Mode", 0))
        index = self.modeCombo.findData(self.__mode)
        if index == -1:
            index = 0
        self.modeCombo.setCurrentIndex(index)
        
        self.__delay = int(
            Preferences.Prefs.settings.value("Snapshot/Delay", 0))
        self.delaySpin.setValue(self.__delay)
        
        if PYQT_VERSION_STR >= "5.0.0":
            from PyQt5.QtCore import QStandardPaths
            picturesLocation = QStandardPaths.writableLocation(
                QStandardPaths.PicturesLocation)
        else:
            from PyQt5.QtGui import QDesktopServices
            picturesLocation = QDesktopServices.storageLocation(
                QDesktopServices.PicturesLocation)
        self.__filename = Preferences.Prefs.settings.value(
            "Snapshot/Filename",
            os.path.join(picturesLocation,
                         self.tr("snapshot") + "1.png"))
        
        self.__grabber = None
        self.__snapshot = QPixmap()
        self.__savedPosition = QPoint()
        self.__modified = False
        self.__locale = QLocale()
        
        self.__grabberWidget = QWidget(None, Qt.X11BypassWindowManagerHint)
        self.__grabberWidget.move(-10000, -10000)
        self.__grabberWidget.installEventFilter(self)
        
        self.__initFileFilters()
        
        self.__initShortcuts()
        
        self.preview.startDrag.connect(self.__dragSnapshot)
        
        from .SnapshotTimer import SnapshotTimer
        self.__grabTimer = SnapshotTimer()
        self.__grabTimer.timeout.connect(self.__grabTimerTimeout)
        self.__updateTimer = QTimer()
        self.__updateTimer.setSingleShot(True)
        self.__updateTimer.timeout.connect(self.__updatePreview)
        
        self.__updateCaption()
        self.takeButton.setFocus()
    
    def __initFileFilters(self):
        """
        Private method to define the supported image file filters.
        """
        filters = {
            'bmp': self.tr("Windows Bitmap File (*.bmp)"),
            'gif': self.tr("Graphic Interchange Format File (*.gif)"),
            'ico': self.tr("Windows Icon File (*.ico)"),
            'jpg': self.tr("JPEG File (*.jpg)"),
            'mng': self.tr("Multiple-Image Network Graphics File (*.mng)"),
            'pbm': self.tr("Portable Bitmap File (*.pbm)"),
            'pcx': self.tr("Paintbrush Bitmap File (*.pcx)"),
            'pgm': self.tr("Portable Graymap File (*.pgm)"),
            'png': self.tr("Portable Network Graphics File (*.png)"),
            'ppm': self.tr("Portable Pixmap File (*.ppm)"),
            'sgi': self.tr("Silicon Graphics Image File (*.sgi)"),
            'svg': self.tr("Scalable Vector Graphics File (*.svg)"),
            'tga': self.tr("Targa Graphic File (*.tga)"),
            'tif': self.tr("TIFF File (*.tif)"),
            'xbm': self.tr("X11 Bitmap File (*.xbm)"),
            'xpm': self.tr("X11 Pixmap File (*.xpm)"),
        }
        
        outputFormats = []
        writeFormats = QImageWriter.supportedImageFormats()
        for writeFormat in writeFormats:
            try:
                outputFormats.append(filters[bytes(writeFormat).decode()])
            except KeyError:
                pass
        outputFormats.sort()
        self.__outputFilter = ';;'.join(outputFormats)
        
        self.__defaultFilter = filters['png']
    
    def __initShortcuts(self):
        """
        Private method to initialize the keyboard shortcuts.
        """
        self.__quitShortcut = QShortcut(
            QKeySequence(QKeySequence.Quit), self, self.close)
        
        self.__copyShortcut = QShortcut(
            QKeySequence(QKeySequence.Copy), self,
            self.copyButton.animateClick)
        
        self.__quickSaveShortcut = QShortcut(
            QKeySequence(Qt.Key_Q), self, self.__quickSave)
        
        self.__save1Shortcut = QShortcut(
            QKeySequence(QKeySequence.Save), self,
            self.saveButton.animateClick)
        self.__save2Shortcut = QShortcut(
            QKeySequence(Qt.Key_S), self, self.saveButton.animateClick)
        
        self.__grab1Shortcut = QShortcut(
            QKeySequence(QKeySequence.New), self, self.takeButton.animateClick)
        self.__grab2Shortcut = QShortcut(
            QKeySequence(Qt.Key_N), self, self.takeButton.animateClick)
        self.__grab3Shortcut = QShortcut(
            QKeySequence(Qt.Key_Space), self, self.takeButton.animateClick)
    
    def __quickSave(self):
        """
        Private slot to save the snapshot bypassing the file selection dialog.
        """
        if not self.__snapshot.isNull():
            while os.path.exists(self.__filename):
                self.__autoIncFilename()
            
            if self.__saveImage(self.__filename):
                self.__modified = False
                self.__autoIncFilename()
                self.__updateCaption()
    
    @pyqtSlot()
    def on_saveButton_clicked(self):
        """
        Private slot to save the snapshot.
        """
        if not self.__snapshot.isNull():
            while os.path.exists(self.__filename):
                self.__autoIncFilename()
            
            fileName, selectedFilter = E5FileDialog.getSaveFileNameAndFilter(
                self,
                self.tr("Save Snapshot"),
                self.__filename,
                self.__outputFilter,
                self.__defaultFilter,
                E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite))
            if not fileName:
                return
            
            ext = QFileInfo(fileName).suffix()
            if not ext:
                ex = selectedFilter.split("(*")[1].split(")")[0]
                if ex:
                    fileName += ex
            
            if self.__saveImage(fileName):
                self.__modified = False
                self.__filename = fileName
                self.__autoIncFilename()
                self.__updateCaption()
    
    def __saveImage(self, fileName):
        """
        Private method to save the snapshot.
        
        @param fileName name of the file to save to (string)
        @return flag indicating success (boolean)
        """
        if QFileInfo(fileName).exists():
            res = E5MessageBox.yesNo(
                self,
                self.tr("Save Snapshot"),
                self.tr("<p>The file <b>{0}</b> already exists."
                        " Overwrite it?</p>").format(fileName),
                icon=E5MessageBox.Warning)
            if not res:
                return False
        
        file = QFile(fileName)
        if not file.open(QFile.WriteOnly):
            E5MessageBox.warning(
                self, self.tr("Save Snapshot"),
                self.tr("Cannot write file '{0}:\n{1}.")
                .format(fileName, file.errorString()))
            return False
        
        ok = self.__snapshot.save(file)
        file.close()
        
        if not ok:
            E5MessageBox.warning(
                self, self.tr("Save Snapshot"),
                self.tr("Cannot write file '{0}:\n{1}.")
                .format(fileName, file.errorString()))
        
        return ok
    
    def __autoIncFilename(self):
        """
        Private method to auto-increment the file name.
        """
        # Extract the file name
        name = os.path.basename(self.__filename)
        
        # If the name contains a number, then increment it.
        numSearch = QRegExp("(^|[^\\d])(\\d+)")
        # We want to match as far left as possible, and when the number is
        # at the start of the name.
        
        # Does it have a number?
        start = numSearch.lastIndexIn(name)
        if start != -1:
            # It has a number, increment it.
            start = numSearch.pos(2)    # Only the second group is of interest.
            numAsStr = numSearch.capturedTexts()[2]
            number = "{0:0{width}d}".format(
                int(numAsStr) + 1, width=len(numAsStr))
            name = name[:start] + number + name[start + len(numAsStr):]
        else:
            # no number
            start = name.rfind('.')
            if start != -1:
                # has a '.' somewhere, e.g. it has an extension
                name = name[:start] + '1' + name[start:]
            else:
                # no extension, just tack it on to the end
                name += '1'
        
        self.__filename = os.path.join(os.path.dirname(self.__filename), name)
        self.__updateCaption()
    
    @pyqtSlot()
    def on_takeButton_clicked(self):
        """
        Private slot to take a snapshot.
        """
        self.__mode = self.modeCombo.itemData(self.modeCombo.currentIndex())
        self.__delay = self.delaySpin.value()
        
        self.__savedPosition = self.pos()
        self.hide()
        
        if self.__delay:
            self.__grabTimer.start(self.__delay)
        else:
            QTimer.singleShot(200, self.__startUndelayedGrab)
    
    def __grabTimerTimeout(self):
        """
        Private slot to perform a delayed grab operation.
        """
        if self.__mode == SnapWidget.ModeRectangle:
            self.__grabRectangle()
        elif self.__mode == SnapWidget.ModeEllipse:
            self.__grabEllipse()
        elif self.__mode == SnapWidget.ModeFreehand:
            self.__grabFreehand()
        else:
            self.__performGrab()
    
    def __startUndelayedGrab(self):
        """
        Private slot to perform an undelayed grab operation.
        """
        if self.__mode == SnapWidget.ModeRectangle:
            self.__grabRectangle()
        elif self.__mode == SnapWidget.ModeEllipse:
            self.__grabEllipse()
        elif self.__mode == SnapWidget.ModeFreehand:
            self.__grabFreehand()
        else:
            if Globals.isMacPlatform():
                self.__performGrab()
            else:
                self.__grabberWidget.show()
                self.__grabberWidget.grabMouse(Qt.CrossCursor)
    
    def __grabRectangle(self):
        """
        Private method to grab a rectangular screen region.
        """
        from .SnapshotRegionGrabber import SnapshotRegionGrabber
        self.__grabber = SnapshotRegionGrabber(
            mode=SnapshotRegionGrabber.Rectangle)
        self.__grabber.grabbed.connect(self.__captured)
    
    def __grabEllipse(self):
        """
        Private method to grab an elliptical screen region.
        """
        from .SnapshotRegionGrabber import SnapshotRegionGrabber
        self.__grabber = SnapshotRegionGrabber(
            mode=SnapshotRegionGrabber.Ellipse)
        self.__grabber.grabbed.connect(self.__captured)
    
    def __grabFreehand(self):
        """
        Private method to grab a non-rectangular screen region.
        """
        from .SnapshotFreehandGrabber import SnapshotFreehandGrabber
        self.__grabber = SnapshotFreehandGrabber()
        self.__grabber.grabbed.connect(self.__captured)
    
    def __performGrab(self):
        """
        Private method to perform a screen grab other than a selected region.
        """
        self.__grabberWidget.releaseMouse()
        self.__grabberWidget.hide()
        self.__grabTimer.stop()
        
        if self.__mode == SnapWidget.ModeFullscreen:
            desktop = QApplication.desktop()
            if qVersion() >= "5.0.0":
                self.__snapshot = QApplication.screens()[0].grabWindow(
                    desktop.winId(), desktop.x(), desktop.y(),
                    desktop.width(), desktop.height())
            else:
                self.__snapshot = QPixmap.grabWindow(
                    desktop.winId(), desktop.x(), desktop.y(),
                    desktop.width(), desktop.height())
        elif self.__mode == SnapWidget.ModeScreen:
            desktop = QApplication.desktop()
            screenId = desktop.screenNumber(QCursor.pos())
            geom = desktop.screenGeometry(screenId)
            x = geom.x()
            y = geom.y()
            if qVersion() >= "5.0.0":
                self.__snapshot = QApplication.screens()[0].grabWindow(
                    desktop.winId(), x, y, geom.width(), geom.height())
            else:
                self.__snapshot = QPixmap.grabWindow(
                    desktop.winId(), x, y, geom.width(), geom.height())
        else:
            self.__snapshot = QPixmap()
        
        self.__redisplay()
        self.__modified = True
        self.__updateCaption()
    
    def __redisplay(self):
        """
        Private method to redisplay the window.
        """
        self.__updatePreview()
        QApplication.restoreOverrideCursor()
        if not self.__savedPosition.isNull():
            self.move(self.__savedPosition)
        self.show()
        self.raise_()
        
        self.saveButton.setEnabled(not self.__snapshot.isNull())
        self.copyButton.setEnabled(not self.__snapshot.isNull())
        self.copyPreviewButton.setEnabled(not self.__snapshot.isNull())
    
    @pyqtSlot()
    def on_copyButton_clicked(self):
        """
        Private slot to copy the snapshot to the clipboard.
        """
        if not self.__snapshot.isNull():
            QApplication.clipboard().setPixmap(QPixmap(self.__snapshot))
    
    @pyqtSlot()
    def on_copyPreviewButton_clicked(self):
        """
        Private slot to copy the snapshot preview to the clipboard.
        """
        QApplication.clipboard().setPixmap(self.preview.pixmap())
    
    def __captured(self, pixmap):
        """
        Private slot to show a preview of the snapshot.
        
        @param pixmap pixmap of the snapshot (QPixmap)
        """
        self.__grabber.close()
        self.__snapshot = QPixmap(pixmap)
        
        self.__grabber.grabbed.disconnect(self.__captured)
        self.__grabber = None
        
        self.__redisplay()
        self.__modified = True
        self.__updateCaption()
    
    def __updatePreview(self):
        """
        Private slot to update the preview picture.
        """
        self.preview.setToolTip(self.tr(
            "Preview of the snapshot image ({0} x {1})").format(
            self.__locale.toString(self.__snapshot.width()),
            self.__locale.toString(self.__snapshot.height()))
        )
        self.preview.setPreview(self.__snapshot)
        self.preview.adjustSize()
    
    def resizeEvent(self, evt):
        """
        Protected method handling a resizing of the window.
        
        @param evt resize event (QResizeEvent)
        """
        self.__updateTimer.start(200)
    
    def __dragSnapshot(self):
        """
        Private slot handling the dragging of the preview picture.
        """
        drag = QDrag(self)
        mimeData = QMimeData()
        mimeData.setImageData(self.__snapshot)
        drag.setMimeData(mimeData)
        drag.setPixmap(self.preview.pixmap())
        drag.exec_(Qt.CopyAction)
    
    def eventFilter(self, obj, evt):
        """
        Public method to handle event for other objects.
        
        @param obj reference to the object (QObject)
        @param evt reference to the event (QEvent)
        @return flag indicating that the event should be filtered out (boolean)
        """
        if obj == self.__grabberWidget and \
                evt.type() == QEvent.MouseButtonPress:
            if QWidget.mouseGrabber() != self.__grabberWidget:
                return False
            if evt.button() == Qt.LeftButton:
                self.__performGrab()
        
        return False
    
    def closeEvent(self, evt):
        """
        Protected method handling the close event.
        
        @param evt close event (QCloseEvent)
        """
        if self.__modified:
            res = E5MessageBox.question(
                self,
                self.tr("eric6 Snapshot"),
                self.tr(
                    """The application contains an unsaved snapshot."""),
                E5MessageBox.StandardButtons(
                    E5MessageBox.Abort |
                    E5MessageBox.Discard |
                    E5MessageBox.Save))
            if res == E5MessageBox.Abort:
                evt.ignore()
                return
            elif res == E5MessageBox.Save:
                self.on_saveButton_clicked()
        
        Preferences.Prefs.settings.setValue(
            "Snapshot/Delay", self.delaySpin.value())
        Preferences.Prefs.settings.setValue(
            "Snapshot/Mode",
            self.modeCombo.itemData(self.modeCombo.currentIndex()))
        Preferences.Prefs.settings.setValue(
            "Snapshot/Filename", self.__filename)
        Preferences.Prefs.settings.sync()
    
    def __updateCaption(self):
        """
        Private method to update the window caption.
        """
        self.setWindowTitle("{0}[*] - {1}".format(
            os.path.basename(self.__filename),
            self.tr("eric6 Snapshot")))
        self.setWindowModified(self.__modified)
        self.pathNameEdit.setText(os.path.dirname(self.__filename))
Esempio n. 42
0
class Viewer(QtMainWindow):
    jobAdded = Signal()
    jobFinished = Signal()

    def __init__(self, weboob, parent=None):
        super(Viewer, self).__init__(parent)

        self.ui = Ui_Viewer()
        self.ui.setupUi(self)
        self.ui.prevButton.clicked.connect(self.prev)
        self.ui.nextButton.clicked.connect(self.next)
        self.ui.firstButton.clicked.connect(self.first)
        self.ui.lastButton.clicked.connect(self.last)
        self.ui.actionZoomIn.triggered.connect(self.zoomIn)
        self.ui.actionZoomOut.triggered.connect(self.zoomOut)
        self.ui.actionFullSize.triggered.connect(self.zoomFullSize)
        self.ui.actionFitWindow.triggered.connect(self.zoomFit)

        self.ui.actionSaveImage.setShortcut(QKeySequence.Save)
        self.ui.actionSaveImage.triggered.connect(self.saveImage)
        self.ui.actionClose.setShortcut(QKeySequence.Close)
        self.ui.actionClose.triggered.connect(self.close)

        self.model = None
        self.current = None
        self.total = 0
        self.zoomFactor = 1
        self.zoomMode = ZOOM_FACTOR
        self.weboob = weboob

    def setData(self, model, qidx):
        self.model = model
        self.current = QPersistentModelIndex(qidx)

        self.model.rowsInserted.connect(self.updatePos)
        self.model.rowsRemoved.connect(self.updatePos)
        self.model.rowsInserted.connect(self.updateNavButtons)
        self.model.rowsRemoved.connect(self.updateNavButtons)
        self.model.dataChanged.connect(self._dataChanged)
        self.model.modelReset.connect(self.disable)

        self.updateImage()

    @Slot()
    def disable(self):
        self.setEnabled(False)

    def updateNavButtons(self):
        prev = self.current.row() > 0
        self.ui.prevButton.setEnabled(prev)
        self.ui.firstButton.setEnabled(prev)
        next = self.current.row() < self.total - 1
        self.ui.nextButton.setEnabled(next)
        self.ui.lastButton.setEnabled(next)

    def updatePos(self):
        self.total = self.model.rowCount(self.current.parent())
        self.ui.posLabel.setText('%d / %d' % (self.current.row() + 1, self.total))

    def updateImage(self):
        self.updatePos()
        self.updateNavButtons()

        obj = self.current.data(ResultModel.RoleObject)

        if obj.data is NotLoaded:
            self.model.fillObj(obj, ['data'], QModelIndex(self.current))
            self.pixmap = None
        elif obj.data:
            self.pixmap = QPixmap(QImage.fromData(obj.data))
        else:
            self.pixmap = QPixmap()

        self._rebuildImage()

    @Slot(QModelIndex)
    def _dataChanged(self, qidx):
        if qidx == self.current:
            obj = qidx.data(ResultModel.RoleObject)

            if obj.data:
                self.pixmap = QPixmap(QImage.fromData(obj.data))
            else:
                self.pixmap = QPixmap()
            self._rebuildImage()

    @Slot()
    def next(self):
        new = self.current.sibling(self.current.row() + 1, 0)
        if not new.isValid():
            return
        self.current = QPersistentModelIndex(new)
        self.updateImage()

    @Slot()
    def prev(self):
        if self.current.row() == 0:
            return
        self.current = QPersistentModelIndex(self.current.sibling(self.current.row() - 1, 0))
        self.updateImage()

    @Slot()
    def first(self):
        self.current = QPersistentModelIndex(self.current.sibling(0, 0))
        self.updateImage()

    @Slot()
    def last(self):
        self.current = QPersistentModelIndex(self.current.sibling(self.total - 1, 0))
        self.updateImage()

    @Slot()
    def zoomIn(self):
        self.zoomFactor *= 1.25
        self.zoomMode = ZOOM_FACTOR
        self._rebuildImage()

    @Slot()
    def zoomOut(self):
        self.zoomFactor *= 0.75
        self.zoomMode = ZOOM_FACTOR
        self._rebuildImage()

    @Slot()
    def zoomFullSize(self):
        self.zoomFactor = 1
        self.zoomMode = ZOOM_FACTOR
        self._rebuildImage()

    @Slot()
    def zoomFit(self):
        self.zoomMode = ZOOM_FIT
        self._rebuildImage()

    def resizeEvent(self, ev):
        super(Viewer, self).resizeEvent(ev)
        if self.zoomMode == ZOOM_FIT:
            self._rebuildImage()

    def _rebuildZoom(self):
        if self.zoomMode == ZOOM_FACTOR:
            new_width = int(self.pixmap.width() * self.zoomFactor)
            pixmap = self.pixmap.scaledToWidth(new_width, Qt.SmoothTransformation)
        else:
            new_size = self.ui.scrollArea.viewport().size()
            pixmap = self.pixmap.scaled(new_size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
            self.zoomFactor = pixmap.width() / float(self.pixmap.width())
        return pixmap

    def _rebuildImage(self):
        if self.pixmap is None:
            self.ui.view.setText('Loading...')
            return
        elif self.pixmap.isNull():
            self.ui.view.setText('Image could not be loaded')
            return

        pixmap = self._rebuildZoom()
        self.ui.view.setPixmap(pixmap)

    @Slot()
    def saveImage(self):
        def ext_for_filter(s):
            return re.match(r'(?:[A-Z]+) \(\*\.([a-z]+)\)$', s).group(1)

        if not self.pixmap:
            return

        filters = ['PNG (*.png)', 'JPEG (*.jpg)', 'GIF (*.gif)']

        obj = self.current.data(ResultModel.RoleObject)
        name = '%s.%s' % (obj.title or obj.id or u'', obj.ext or 'png')
        default = filters[0]
        for f in filters:
            if name.endswith(ext_for_filter(f)):
                default = f
        filters = ';;'.join(filters)

        target = os.path.join(self.parent().lastSaveDir, name)
        out, filter = QFileDialog.getSaveFileName(self, 'Save image', target, filters, default)
        if not out:
            return

        ext = ext_for_filter(filter)

        self.parent().lastSaveDir = os.path.dirname(out)
        if not os.path.splitext(out)[1]:
            out = '%s.%s' % (out, ext)

            if os.path.exists(out):
                q = self.tr('%s already exists, are you sure you want to replace it?') % out
                reply = QMessageBox.question(self, self.tr('Overwrite?'), q)
                if reply == QMessageBox.No:
                    return self.saveImage()

        self.pixmap.save(out, ext.upper())