Beispiel #1
0
 def ocrForImage(self, image):
     """
     为截取的图片进行ocr识别
     :param image: QImage
     :return: null
     """
     # Note:子线程里不能对ui界面做改动,ui界面修改只能在主线程中修改,下面注释的做法是错误的
     # self.ui.ocrInfo.setText('识别中......')
     byte = QByteArray()
     buffer = QBuffer(byte)
     buffer.open(QIODevice.WriteOnly)
     image.save(buffer, 'PNG')
     if self.ocrType == ocrType.ocr_general:
         self.result = self.OCR.client.general_detect(
             CIBuffers([byte.data()]))
     elif self.ocrType == ocrType.ocr_handwriting:
         self.result = self.OCR.client.handwriting_detect(
             CIBuffers([byte.data()]))
     elif self.ocrType == ocrType.ocr_idcard:
         self.result = self.OCR.client.idcard_detect(
             CIBuffers([byte.data()]), 0)
     elif self.ocrType == ocrType.ocr_namecard:
         self.result = self.OCR.client.namecard_detect(
             CIBuffers([byte.data()]), 0)
     elif self.ocrType == ocrType.ocr_bankcard:
         self.result = self.OCR.client.bankcard_detect(
             CIBuffers([byte.data()]))
     else:
         pass
     self.processFinished.emit(self.result)
Beispiel #2
0
    def save(self):
        """
        Public method to save the zoom values.
        """
        if not self.__loaded:
            return

        from WebBrowser.WebBrowserWindow import WebBrowserWindow
        if not WebBrowserWindow.isPrivate() and bool(self.__iconDatabasePath):
            db = {}
            for url, icon in self.__iconsDB.items():
                ba = QByteArray()
                buffer = QBuffer(ba)
                buffer.open(QIODevice.WriteOnly)
                icon.pixmap(32).toImage().save(buffer, "PNG")
                db[url] = bytes(buffer.data()).decode(self.__encoding)

            filename = os.path.join(self.__iconDatabasePath,
                                    self.__iconsFileName)
            try:
                f = open(filename, "w")
                json.dump(db, f)
                f.close()
            except (IOError, OSError):
                # ignore silentyl
                pass
Beispiel #3
0
 def QPixmap_to_PIL(self):
     img = self.canvas.pixmap().toImage()
     buffer = QBuffer()
     buffer.open(QBuffer.ReadWrite)
     img.save(buffer, "PNG")
     bytes = io.BytesIO(buffer.data())
     return bytes
Beispiel #4
0
    def export_video(self):
        """Record and save a mp4 video of the current animation"""
        if not EXPORT_AVAILABLE:
            msgbox = QMessageBox(QMessageBox.Information,
                                 "Export not available",
                                 "`imageio` and `ffmpeg` must be installed to export videos")
            return msgbox.exec()

        if not self.timer.isActive():
            msgbox = QMessageBox(QMessageBox.Warning,
                                 "Cannot export animation",
                                 "Cannot export video when speed is 0")
            return msgbox.exec()

        location = QFileDialog.getSaveFileName(self,
                                               "Choose export location",
                                               filter="Video (*.mp4)")

        location = location[0]
        if location == '':
            # No file selected
            msgbox = QMessageBox(QMessageBox.Information,
                                 "Export cancelled",
                                 "No export file given")
            return msgbox.exec()

        if not location.endswith('.mp4'):
            location += '.mp4'
        progress_box = QProgressDialog(
            "Recording export video.\nNote that the larger the period value, "
            "the longer the video.",
            "Cancel",
            1,
            self.halfmax * 2 + 1,
            self)
        progress_box.setWindowModality(Qt.WindowModal)
        # sleep(0.2)  # sometimes the progressbox wouldn't show. this seems to fix
        duration = self.timer.interval()
        with imageio.get_writer(location, format='mp4', mode='I', fps=1000/duration, quality=9) as writer:
            self.frame_no = 1
            for i in range(self.halfmax * 2 + 1):  # TODO check if +1 is correct
                progress_box.setValue(i)
                if progress_box.wasCanceled():
                    remove(location)
                    return
                print(i)
                im_bytes = QByteArray()
                buf = QBuffer(im_bytes)
                buf.open(QIODevice.WriteOnly)
                self.grab().save(buf, 'PNG', 100)
                self.frame_no += 1
                # self.update()
                # frames.append(imageio.imread(im_bytes.data(), 'png'))
                writer.append_data(imageio.imread(im_bytes.data(), 'png'))
        progress_box.setValue(progress_box.maximum())

        msgbox = QMessageBox(QMessageBox.Information,
                             "Information",
                             "Export finished! Saved to {}".format(location))
        msgbox.exec()
Beispiel #5
0
    def get_item(self):
        try:
            emp = Employee()
            emp.emp_no = int(self.le_no.text())
            emp.emp_name = self.le_name.text()
            emp.salary = self.sp_salary.value()
            emp.passwd = self.le_pass1.text()
            # emp.hire_date = self.de_hire_date.date().toString("yyyy-MM-dd")
            emp.hire_date = self.de_hire_date.dateTime().toPyDateTime()
            emp.gender = 1 if self.rb_male.isChecked() else 0
            emp.dept = [dept.dept_no for dept in self.dept_list if self.cb_dept.currentText() == dept.dept_name][0]
            emp.manager = int(self.cb_manager.currentText()[4:-1]) #'조민희(1003)'-> 1003
            emp.title = [title.title_no for title in self.title_list if self.cb_title.currentText() == title.title_name][0]

            ba = QByteArray()
            buff = QBuffer(ba)
            buff.open(QIODevice.WriteOnly)
            pixmap = self.lbl_img.pixmap()
            pixmap.save(buff, 'PNG')
            pixmap_bytes = ba.data()

            emp.pic = pixmap_bytes

            return emp
        except Exception as err:
            print(err)
Beispiel #6
0
    def handlePrint(self, data):
        with renderLock:
            self.document, copies = data
            self.update()

            if platform == "linux":
                bmp = QImage(self.size[0], self.size[1], QImage.Format_Mono)
                self.paintEvent(None, bmp)
                buffer = QBuffer()
                buffer.open(QBuffer.ReadWrite)
                bmp.save(buffer, "BMP")
                img = Image.open(io.BytesIO(buffer.data()))
                img.save("/tmp/image.png")
                for i in range(copies):
                    os.system("lpr /tmp/image.png")
            elif platform == "win32":
                pix = self.grab()
                bmp = QImage(pix)
                buffer = QBuffer()
                buffer.open(QBuffer.ReadWrite)
                bmp.save(buffer, "BMP")
                img = Image.open(io.BytesIO(buffer.data()))
                printerName = win32print.GetDefaultPrinter()
                deviceContext = win32ui.CreateDC()
                deviceContext.CreatePrinterDC(printerName)
                deviceContext.StartDoc("Inventory Label")
                for i in range(copies):
                    deviceContext.StartPage()
                    dib = ImageWin.Dib(img)
                    dib.draw(deviceContext.GetHandleOutput(),
                             (0, 0, self.size[0], self.size[1]))
                    deviceContext.EndPage()
                deviceContext.EndDoc()
                deviceContext.DeleteDC()
Beispiel #7
0
    def run(self):

        self.sock.bind(('', configs['live']['port']))
        self.sock.settimeout(1)

        print('LiveClient bind in ', self.sock.getsockname())

        while not self.stop_run:

            while self.wait_recv:
                try:
                    receive_data = self.sock.recv(1024 * 100)  # , address
                    self.wait_recv = False
                except:
                    pass
            self.wait_recv = True

            if self.stop_run:
                break

            receive_data = zlib.decompress(receive_data)

            byte_array = QByteArray(receive_data)
            buffer = QBuffer(byte_array)
            buffer.open(QIODevice.ReadOnly)
            # 读取图片
            reader = QImageReader(buffer)
            q_img = reader.read()
            if self.stop_run:
                break
            self._screen.emit(q_img)

        self.sock.close()  # 关闭套接字
 def get_plant_name(self, image):
     data = QByteArray()
     buffer = QBuffer(data)
     buffer.open(QIODevice.WriteOnly)
     image = image.toImage()
     image.save(buffer, "jpg")
     return BaiduAPi.get_plant_name(buffer.data())
Beispiel #9
0
def pmap_to_pil_img(pmap):
    buffer = QBuffer()
    buffer.open(QBuffer.ReadWrite)

    img = QImage(pmap)
    img.save(buffer, "PNG")
    return Image.open(io.BytesIO(buffer.data()))
Beispiel #10
0
    def write(self, stream, nodes, mode = MeshWriter.OutputMode.BinaryMode):
        archive = VirtualFile()
        archive.openStream(stream, "application/x-ufp", OpenMode.WriteOnly)

        #Store the g-code from the scene.
        archive.addContentType(extension = "gcode", mime_type = "text/x-gcode")
        gcode_textio = StringIO() #We have to convert the g-code into bytes.
        PluginRegistry.getInstance().getPluginObject("GCodeWriter").write(gcode_textio, None)
        gcode = archive.getStream("/3D/model.gcode")
        gcode.write(gcode_textio.getvalue().encode("UTF-8"))
        archive.addRelation(virtual_path = "/3D/model.gcode", relation_type = "http://schemas.ultimaker.org/package/2018/relationships/gcode")

        #Store the thumbnail.
        if self._snapshot:
            archive.addContentType(extension = "png", mime_type = "image/png")
            thumbnail = archive.getStream("/Metadata/thumbnail.png")

            thumbnail_buffer = QBuffer()
            thumbnail_buffer.open(QBuffer.ReadWrite)
            thumbnail_image = self._snapshot
            thumbnail_image.save(thumbnail_buffer, "PNG")

            thumbnail.write(thumbnail_buffer.data())
            archive.addRelation(virtual_path = "/Metadata/thumbnail.png", relation_type = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail", origin = "/3D/model.gcode")
        else:
            Logger.log("d", "Thumbnail not created, cannot save it")

        archive.close()
        return True
Beispiel #11
0
 def mimeData(self, indexes):
     """
     Public method to return the mime data.
     
     @param indexes list of indexes (QModelIndexList)
     @return mime data (QMimeData)
     """
     from .XbelWriter import XbelWriter
     
     data = QByteArray()
     stream = QDataStream(data, QIODevice.WriteOnly)
     urls = []
     
     for index in indexes:
         if index.column() != 0 or not index.isValid():
             continue
         
         encodedData = QByteArray()
         buffer = QBuffer(encodedData)
         buffer.open(QIODevice.ReadWrite)
         writer = XbelWriter()
         parentNode = self.node(index)
         writer.write(buffer, parentNode)
         stream << encodedData
         urls.append(index.data(self.UrlRole))
     
     mdata = QMimeData()
     mdata.setData(self.MIMETYPE, data)
     mdata.setUrls(urls)
     return mdata
Beispiel #12
0
 def dropMimeData(self, data, action, row, column, parent):
     """
     Public method to accept the mime data of a drop action.
     
     @param data reference to the mime data (QMimeData)
     @param action drop action requested (Qt.DropAction)
     @param row row number (integer)
     @param column column number (integer)
     @param parent index of the parent node (QModelIndex)
     @return flag indicating successful acceptance of the data (boolean)
     """
     if action == Qt.IgnoreAction:
         return True
     
     if column > 0:
         return False
     
     parentNode = self.node(parent)
     
     if not data.hasFormat(self.MIMETYPE):
         if not data.hasUrls():
             return False
         
         from .BookmarkNode import BookmarkNode
         node = BookmarkNode(BookmarkNode.Bookmark, parentNode)
         node.url = bytes(data.urls()[0].toEncoded()).decode()
         
         if data.hasText():
             node.title = data.text()
         else:
             node.title = node.url
         
         self.__bookmarksManager.addBookmark(parentNode, node, row)
         return True
     
     ba = data.data(self.MIMETYPE)
     stream = QDataStream(ba, QIODevice.ReadOnly)
     if stream.atEnd():
         return False
     
     undoStack = self.__bookmarksManager.undoRedoStack()
     undoStack.beginMacro("Move Bookmarks")
     
     from .XbelReader import XbelReader
     while not stream.atEnd():
         encodedData = QByteArray()
         stream >> encodedData
         buffer = QBuffer(encodedData)
         buffer.open(QIODevice.ReadOnly)
         
         reader = XbelReader()
         rootNode = reader.read(buffer)
         for bookmarkNode in rootNode.children():
             rootNode.remove(bookmarkNode)
             row = max(0, row)
             self.__bookmarksManager.addBookmark(
                 parentNode, bookmarkNode, row)
             self.__endMacro = True
     
     return True
Beispiel #13
0
    def loadFromMemory(self):
        """ This slot function is called in the second Dialog process, when the
        user presses the "Load Image from Shared Memory" button.  First, it
        attaches the process to the shared memory segment created by the first
        Dialog process.  Then it locks the segment for exclusive access, copies
        the image data from the segment into a QBuffer, and streams the QBuffer
        into a QImage.  Then it unlocks the shared memory segment, detaches
        from it, and finally displays the QImage in the Dialog.
        """

        if not self.sharedMemory.attach():
            self.ui.label.setText(
                    "Unable to attach to shared memory segment.\nLoad an "
                    "image first.")
            return
 
        buf = QBuffer()
        ins = QDataStream(buf)
        image = QImage()

        self.sharedMemory.lock()
        buf.setData(self.sharedMemory.constData())
        buf.open(QBuffer.ReadOnly)
        ins >> image
        self.sharedMemory.unlock()
        self.sharedMemory.detach()

        self.ui.label.setPixmap(QPixmap.fromImage(image))
Beispiel #14
0
 def pixmapToPIL(self):
     pmap = self.image.pixmap()
     imageBuffer = QBuffer()
     imageBuffer.open(QBuffer.ReadWrite)
     pmap.save(imageBuffer, "PNG")
     img = Image.open(io.BytesIO(imageBuffer.data()))
     return img
Beispiel #15
0
    def _addIcon(self):
        filter_ = self.tr("Images (*.jpg *.jpeg *.bmp *.png *.tiff *.gif);;"
                          "All files (*.*)")
        fileName, _selectedFilter = QFileDialog.getOpenFileName(self,
                self.tr("Open File"), self.latestDir,
                filter_)
        if fileName:
            file_info = QFileInfo(fileName)
            self.latestDir = file_info.absolutePath()

            image = QImage()
            if image.load(fileName):
                maxWidth = 22
                maxHeight = 15
                if image.width() > maxWidth or image.height() > maxHeight:
                    scaledImage = image.scaled(maxWidth, maxHeight,
                            Qt.KeepAspectRatio, Qt.SmoothTransformation)
                else:
                    scaledImage = image

                ba = QByteArray()
                buffer = QBuffer(ba)
                buffer.open(QIODevice.WriteOnly)
                scaledImage.save(buffer, 'png')

                model = self.model()
                index = model.index(self.selectedIndex().row(), model.fieldIndex('icon'))
                model.setData(index, ba)
    def _encodeSnapshot(self, snapshot):

        Major = 0
        Minor = 0
        try:
            Major = int(CuraVersion.split(".")[0])
            Minor = int(CuraVersion.split(".")[1])
        except:
            pass

        if Major < 5:
            from PyQt5.QtCore import QByteArray, QIODevice, QBuffer
        else:
            from PyQt6.QtCore import QByteArray, QIODevice, QBuffer

        Logger.log("d", "Encoding thumbnail image...")
        try:
            thumbnail_buffer = QBuffer()
            if Major < 5:
                thumbnail_buffer.open(QBuffer.ReadWrite)
            else:
                thumbnail_buffer.open(QBuffer.OpenModeFlag.ReadWrite)
            thumbnail_image = snapshot
            thumbnail_image.save(thumbnail_buffer, "JPG")
            base64_bytes = base64.b64encode(thumbnail_buffer.data())
            base64_message = base64_bytes.decode('ascii')
            thumbnail_buffer.close()
            return base64_message
        except Exception:
            Logger.logException("w", "Failed to encode snapshot image")
Beispiel #17
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"))
Beispiel #18
0
  def saveImage(self, width, height, dataUrl="", tx=0, ty=0, intermediate=False):
    image = None
    if dataUrl:
      ba = QByteArray.fromBase64(dataUrl[22:].encode("ascii"))
      if tx or ty:
        image = QImage()
        image.loadFromData(ba)

    else:
      image = QImage(width, height, QImage.Format_ARGB32_Premultiplied)
      painter = QPainter(image)
      self._page.mainFrame().render(painter)
      painter.end()

    if tx or ty:
      img = QImage(width - tx, height - ty, QImage.Format_ARGB32_Premultiplied)
      painter = QPainter(img)
      painter.drawImage(tx, ty, image)
      painter.end()
      image = img

    # image to byte array
    if image:
      ba = QByteArray()
      buf = QBuffer(ba)
      buf.open(QIODevice.WriteOnly)
      image.save(buf, "PNG")

    dataType = q3dconst.BIN_INTERMEDIATE_IMAGE if intermediate else q3dconst.BIN_SCENE_IMAGE
    self.iface.respond(ba.data(), {"dataType": dataType, "renderId": self.renderId})    # q3dconst.FORMAT_BINARY
Beispiel #19
0
    def sendNNrequest(self):
        # get pixamp bytes in tiff extension
        original_img_bytes = QByteArray()
        original_img_buff = QBuffer(original_img_bytes)
        original_img_buff.open(QIODevice.WriteOnly)
        extention = os.path.splitext(self.metafileobj.origFilename)[1][1:]
        self.cellPixmapUnscaled.save(original_img_buff, extention)
        original_img_buff.close()

        payload = {
            'id': str(client_config['id']),
            'code': ReqCodes.GET_NN_PREDICTION._value_,
            'image': str(base64.b64encode(original_img_bytes.data()), 'utf-8'),
            'random_seed': random.randint(0, 999999999)
        }

        json_data = json.dumps(payload)
        try:
            response = requests.post(client_config['url'], data=json_data, headers=client_config['headers'])
            pred_cells_num = response['cells_count']
            self.neuralCellCount.setText('Предсказанное количество: ' + pred_cells_num)
            self.neuralCellCount.show()
            neural_image_bytes = base64.b64decode(response['image'])
            self.neuralImage.loadFromData(neural_image_bytes, 'TIFF')
            self.isNeuralImage = True
            self.neuralImage.setText('Спрятать изображение')
            self.haveWeNeuralImage = True
        except:
            self.makeErrMessage("Произшала ошибка при взаимодействии с сервером, попробуйте позже.")
        finally:
            del original_img_bytes
            del original_img_buff
            del payload
            del json_data
Beispiel #20
0
def get_frame_with_color_info(color: QColor, size=SIZE, rounded=True, as_bytes=False) -> Union[QImage, bytes]:
    image = QImage(size, size, QImage.Format_ARGB32)
    image.fill(Qt.transparent)

    painter = QPainter(image)
    painter.setRenderHint(QPainter.HighQualityAntialiasing)
    painter.setPen(Qt.NoPen)
    painter.setBrush(color)

    if rounded:
        painter.drawRoundedRect(0, 0, image.width(), image.height(), RADIUS, RADIUS, Qt.RelativeSize)
    else:
        painter.drawRect(0, 0, image.width(), image.height())

    draw_hex(painter, size, color)
    draw_rgb(painter, size, color)

    painter.end()

    if as_bytes:
        ba = QByteArray()
        buff = QBuffer(ba)
        buff.open(QIODevice.WriteOnly)
        image.save(buff, "PNG")
        return ba.data()

    return image
Beispiel #21
0
    async def injectQaIcon(self, ipfsop, idx, iconPath):
        """
        Inject a QtAwesome font in the IPFS repository
        (PNG, fixed-size 128x128)
        """

        icon = self.itemIcon(idx)

        try:
            size = QSize(128, 128)
            pixmap = icon.pixmap(size)
            array = QByteArray()
            buffer = QBuffer(array)
            buffer.open(QIODevice.WriteOnly)
            pixmap.save(buffer, 'png')
            buffer.close()
        except Exception as err:
            log.debug('QtAwesome inject error: {}'.format(str(err)))
        else:
            entry = await ipfsop.addBytes(array.data(), offline=self.offline)
            if entry:
                self.iconCid = entry['Hash']
                self.iconSelected.emit(self.iconCid)
                self.setToolTip(self.iconCid)
                return True
Beispiel #22
0
    def mimeData(self, indexes):
        """
        Public method to return the mime data.
        
        @param indexes list of indexes (QModelIndexList)
        @return mime data (QMimeData)
        """
        from .XbelWriter import XbelWriter

        data = QByteArray()
        stream = QDataStream(data, QIODevice.WriteOnly)
        urls = []

        for index in indexes:
            if index.column() != 0 or not index.isValid():
                continue

            encodedData = QByteArray()
            buffer = QBuffer(encodedData)
            buffer.open(QIODevice.ReadWrite)
            writer = XbelWriter()
            parentNode = self.node(index)
            writer.write(buffer, parentNode)
            stream << encodedData
            urls.append(index.data(self.UrlRole))

        mdata = QMimeData()
        mdata.setData(self.MIMETYPE, data)
        mdata.setUrls(urls)
        return mdata
Beispiel #23
0
    def loadFromMemory(self):
        """ This slot function is called in the second Dialog process, when the
        user presses the "Load Image from Shared Memory" button.  First, it
        attaches the process to the shared memory segment created by the first
        Dialog process.  Then it locks the segment for exclusive access, copies
        the image data from the segment into a QBuffer, and streams the QBuffer
        into a QImage.  Then it unlocks the shared memory segment, detaches
        from it, and finally displays the QImage in the Dialog.
        """

        if not self.sharedMemory.attach():
            self.ui.label.setText(
                "Unable to attach to shared memory segment.\nLoad an "
                "image first.")
            return

        buf = QBuffer()
        ins = QDataStream(buf)
        image = QImage()

        self.sharedMemory.lock()
        buf.setData(self.sharedMemory.constData())
        buf.open(QBuffer.ReadOnly)
        ins >> image
        self.sharedMemory.unlock()
        self.sharedMemory.detach()

        self.ui.label.setPixmap(QPixmap.fromImage(image))
Beispiel #24
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"))
Beispiel #25
0
    def eps(self, filename, rect=None, resolution=72.0, paperColor=None):
        """Create a EPS (Encapsulated Postscript) file for the selected rect or the whole page.

        This needs the popplerqt5 module.
        The filename may be a string or a QIODevice object. The rectangle is
        relative to our top-left position. Normally vector graphics are
        rendered, but in cases where that is not possible, the resolution will
        be used to determine the DPI for the generated rendering.

        """
        buf = QBuffer()
        buf.open(QBuffer.WriteOnly)
        success = self.pdf(buf, rect, resolution, paperColor)
        buf.close()
        if success:
            from . import poppler
            for pdf in poppler.PopplerPage.load(buf.data()):
                ps = pdf.document.psConverter()
                ps.setPageList([pdf.pageNumber + 1])
                if isinstance(filename, str):
                    ps.setOutputFileName(filename)
                else:
                    ps.setOutputDevice(filename)
                try:
                    ps.setPSOptions(ps.PSOption(ps.Printing
                                                | ps.StrictMargins))
                    ps.setPSOptions(
                        ps.PSOption(ps.Printing | ps.StrictMargins
                                    | ps.PrintToEPS))
                except AttributeError:
                    pass
                ps.setVDPI(resolution)
                ps.setHDPI(resolution)
                return ps.convert()
        return False
Beispiel #26
0
 def dropEvent(self, event):
     mimeData = event.mimeData()
     if mimeData.hasUrls():
         paths = mimeData.urls()
         # pick just one image
         path = paths[0].toLocalFile()
         fileName = os.path.basename(path)
         with open(path, "rb") as imgFile:
             data = imgFile.read()
         ext = os.path.splitext(path)[1][1:]
         # TODO: make sure we cleanup properly when replacing an image with
         # another
         if ext.lower() != "png":
             # convert
             img = QImage(path)
             data = QByteArray()
             buffer = QBuffer(data)
             buffer.open(QIODevice.WriteOnly)
             img.save(buffer, 'PNG')
             # format
             data = bytearray(data)
             fileName = "%s.png" % os.path.splitext(fileName)[0]
         imageSet = self._glyph.font.images
         try:
             imageSet[fileName] = data
         except Exception as e:
             errorReports.showCriticalException(e)
             return
         image = self._glyph.instantiateImage()
         image.fileName = fileName
         event.setAccepted(True)
     else:
         super().dropEvent(event)
Beispiel #27
0
 def encode_image(self, size: QSize = None, *, fmt="PNG") -> bytes:
     """ Render to a bitmap image and convert it to a data stream. """
     im = self.draw_image(size)
     buf = QBuffer()
     buf.open(QIODevice.WriteOnly)
     im.save(buf, fmt)
     return buf.data()
Beispiel #28
0
    def requestStarted(self, job: QWebEngineUrlRequestJob) -> None:
        path = job.requestUrl().path()
        path = os.path.realpath(path)

        print(path)

        if not path:
            job.fail(QWebEngineUrlRequestJob.UrlInvalid)
            return

        if not os.path.exists(path):
            job.fail(QWebEngineUrlRequestJob.UrlNotFound)
            return

        try:
            with open(path, 'rb') as file:
                content_type = mimetypes.guess_type(path)
                buffer = QBuffer(parent=self)

                buffer.open(QIODevice.WriteOnly)
                buffer.write(file.read())
                buffer.seek(0)
                buffer.close()

                job.reply(content_type[0].encode(), buffer)

        except Exception as err:
            raise err
Beispiel #29
0
    def mouseMoveEvent(self, event):
        """ If the mouse moves far enough when the left mouse button is held
            down, start a drag and drop operation.
        """
        if not event.buttons() & Qt.LeftButton:
            return

        if (event.pos() - self.dragStartPosition).manhattanLength() \
             < QApplication.startDragDistance():
            return

        if not self.hasImage:
            return

        drag = QDrag(self)
        mimeData = QMimeData()

        output = QByteArray()
        outputBuffer = QBuffer(output)
        outputBuffer.open(QIODevice.WriteOnly)
        self.imageLabel.pixmap().toImage().save(outputBuffer, 'PNG')
        outputBuffer.close()
        mimeData.setData('image/png', output)

        drag.setMimeData(mimeData)
        drag.setPixmap(self.imageLabel.pixmap().scaled(64, 64, Qt.KeepAspectRatio))
        drag.setHotSpot(QPoint(drag.pixmap().width() / 2,
                                      drag.pixmap().height()))
        drag.start()
    def requestStarted(self, job):
        """Handle a request for a qute: scheme.

        This method must be reimplemented by all custom URL scheme handlers.
        The request is asynchronous and does not need to be handled right away.

        Args:
            job: QWebEngineUrlRequestJob
        """
        url = job.requestUrl()

        if url.scheme() in ['chrome-error', 'chrome-extension']:
            # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-63378
            job.fail(QWebEngineUrlRequestJob.UrlInvalid)
            return

        if not self._check_initiator(job):
            return

        if job.requestMethod() != b'GET':
            job.fail(QWebEngineUrlRequestJob.RequestDenied)
            return

        assert url.scheme() == 'qute'

        log.misc.debug("Got request for {}".format(url.toDisplayString()))
        try:
            mimetype, data = qutescheme.data_for_url(url)
        except qutescheme.Error as e:
            errors = {
                qutescheme.NotFoundError:
                    QWebEngineUrlRequestJob.UrlNotFound,
                qutescheme.UrlInvalidError:
                    QWebEngineUrlRequestJob.UrlInvalid,
                qutescheme.RequestDeniedError:
                    QWebEngineUrlRequestJob.RequestDenied,
                qutescheme.SchemeOSError:
                    QWebEngineUrlRequestJob.UrlNotFound,
                qutescheme.Error:
                    QWebEngineUrlRequestJob.RequestFailed,
            }
            exctype = type(e)
            log.misc.error("{} while handling qute://* URL".format(
                exctype.__name__))
            job.fail(errors[exctype])
        except qutescheme.Redirect as e:
            qtutils.ensure_valid(e.url)
            job.redirect(e.url)
        else:
            log.misc.debug("Returning {} data".format(mimetype))

            # We can't just use the QBuffer constructor taking a QByteArray,
            # because that somehow segfaults...
            # https://www.riverbankcomputing.com/pipermail/pyqt/2016-September/038075.html
            buf = QBuffer(parent=self)
            buf.open(QIODevice.WriteOnly)
            buf.write(data)
            buf.seek(0)
            buf.close()
            job.reply(mimetype.encode('ascii'), buf)
Beispiel #31
0
    def pickle(self):
        """
        Pickle the image into a list containing important information.

        Returns:
            (list): containing
                (str): "Image"
                (float): X position of image.
                (float): Y position of image.
                (str): a string containing image data in base64 encoding.
                (float): scale of the image.
                (bool): true if the image contains a red border,
                    false otherwise.
        """
        if self.data is None:
            ba = QByteArray()
            buffer = QBuffer(ba)
            buffer.open(QIODevice.WriteOnly)
            self.qImage.save(buffer, "PNG")
            pickle = [
                "Image",
                self.x(),
                self.y(),
                str(ba.toBase64().data()),
                self.scale(),
                self.border,
            ]
        else:
            pickle = [
                "Image",
                self.x(),
                self.y(), self.data,
                self.scale(), self.border
            ]
        return pickle
Beispiel #32
0
 def dropEvent(self, event):
     mimeData = event.mimeData()
     if mimeData.hasUrls():
         paths = mimeData.urls()
         # pick just one image
         path = paths[0].toLocalFile()
         fileName = os.path.basename(path)
         with open(path, "rb") as imgFile:
             data = imgFile.read()
         ext = os.path.splitext(path)[1][1:]
         # TODO: make sure we cleanup properly when replacing an image with
         # another
         if ext.lower() != "png":
             # convert
             img = QImage(path)
             data = QByteArray()
             buffer = QBuffer(data)
             buffer.open(QIODevice.WriteOnly)
             img.save(buffer, 'PNG')
             # format
             data = bytearray(data)
             fileName = "%s.png" % os.path.splitext(fileName)[0]
         imageSet = self._glyph.font.images
         try:
             imageSet[fileName] = data
         except Exception as e:
             errorReports.showCriticalException(e)
             return
         image = self._glyph.instantiateImage()
         image.fileName = fileName
         event.setAccepted(True)
     else:
         super().dropEvent(event)
Beispiel #33
0
def picklePixmap(pixmap):
    image = pixmap.toImage()
    byt_arr = QByteArray()
    buffer = QBuffer(byt_arr)
    buffer.open(QIODevice.WriteOnly);
    image.save(buffer, "PNG");
    return byt_arr
Beispiel #34
0
    def mouseMoveEvent(self, event):
        """ If the mouse moves far enough when the left mouse button is held
            down, start a drag and drop operation.
        """
        if not event.buttons() & Qt.LeftButton:
            return

        if (event.pos() - self.dragStartPosition).manhattanLength() \
             < QApplication.startDragDistance():
            return

        if not self.hasImage:
            return

        drag = QDrag(self)
        mimeData = QMimeData()

        output = QByteArray()
        outputBuffer = QBuffer(output)
        outputBuffer.open(QIODevice.WriteOnly)
        self.imageLabel.pixmap().toImage().save(outputBuffer, 'PNG')
        outputBuffer.close()
        mimeData.setData('image/png', output)

        drag.setMimeData(mimeData)
        drag.setPixmap(self.imageLabel.pixmap().scaled(64, 64, Qt.KeepAspectRatio))
        drag.setHotSpot(QPoint(drag.pixmap().width() / 2,
                                      drag.pixmap().height()))
        drag.start()
Beispiel #35
0
    def dropMimeData(self, data, action, row, column, parent):
        """
        Public method to accept the mime data of a drop action.
        
        @param data reference to the mime data (QMimeData)
        @param action drop action requested (Qt.DropAction)
        @param row row number (integer)
        @param column column number (integer)
        @param parent index of the parent node (QModelIndex)
        @return flag indicating successful acceptance of the data (boolean)
        """
        if action == Qt.IgnoreAction:
            return True

        if column > 0:
            return False

        parentNode = self.node(parent)

        if not data.hasFormat(self.MIMETYPE):
            if not data.hasUrls():
                return False

            from .BookmarkNode import BookmarkNode
            node = BookmarkNode(BookmarkNode.Bookmark, parentNode)
            node.url = bytes(data.urls()[0].toEncoded()).decode()

            if data.hasText():
                node.title = data.text()
            else:
                node.title = node.url

            self.__bookmarksManager.addBookmark(parentNode, node, row)
            return True

        ba = data.data(self.MIMETYPE)
        stream = QDataStream(ba, QIODevice.ReadOnly)
        if stream.atEnd():
            return False

        undoStack = self.__bookmarksManager.undoRedoStack()
        undoStack.beginMacro("Move Bookmarks")

        from .XbelReader import XbelReader
        while not stream.atEnd():
            encodedData = QByteArray()
            stream >> encodedData
            buffer = QBuffer(encodedData)
            buffer.open(QIODevice.ReadOnly)

            reader = XbelReader()
            rootNode = reader.read(buffer)
            for bookmarkNode in rootNode.children():
                rootNode.remove(bookmarkNode)
                row = max(0, row)
                self.__bookmarksManager.addBookmark(parentNode, bookmarkNode,
                                                    row)
                self.__endMacro = True

        return True
    def add_request(self, request):
        if len(self.requests_in_flight) > self.max_in_flight:
            self.evict_timed_out_requests()

        self.requests_in_flight[id(request)] = request
        log = [request, 0]
        performed_requests.append(log)

        # qt_request is managed by QNetworkAccessManager, so we don't have to
        qt_request = QNetworkRequest(QUrl(request.url))
        qt_request.setPriority(request.priority)
        qt_request.setHeader(QNetworkRequest.ContentTypeHeader,
                             "application/x-www-form-urlencoded")
        qt_request.setRawHeader(b'X-Api-Key', self.key)

        buf = QBuffer()
        if request.raw_data:
            buf.setData(request.raw_data)
        buf.open(QIODevice.ReadOnly)

        request.reply = self.sendCustomRequest(qt_request,
                                               request.method.encode("utf8"),
                                               buf)
        buf.setParent(request.reply)

        connect(request.reply.finished, lambda: request.on_finished(request))
Beispiel #37
0
 def _image_to_byte_array(self, image) -> QByteArray:
     byte_array = QByteArray()
     buffer = QBuffer(byte_array)
     buffer.open(QIODevice.WriteOnly)
     image.save(buffer, 'png')
     buffer.close()
     return byte_array 
Beispiel #38
0
def image_and_format_from_data(data):
    ' Create an image object from the specified data which should be a bytestring and also return the format of the image '
    ba = QByteArray(data)
    buf = QBuffer(ba)
    buf.open(QBuffer.ReadOnly)
    r = QImageReader(buf)
    fmt = bytes(r.format()).decode('utf-8')
    return r.read(), fmt
Beispiel #39
0
    def take_screenshot(self):
        byte_array = QByteArray()
        buffer = QBuffer(byte_array)
        buffer.open(QIODevice.WriteOnly)

        image = self.__screen.grabWindow(QApplication.desktop().winId())
        image.save(buffer, "PNG")

        return str(byte_array.toBase64())[1:]
Beispiel #40
0
    def fillImageFaster(self, begin, paint, current, image):

        buffer = QBuffer()
        buffer.open(QBuffer.ReadWrite)

        image.save(buffer, "PNG")

        pil_im = Image.open(io.BytesIO(buffer.data()))
        ImageDraw.floodfill(pil_im, begin, (paint.red(), paint.green(), paint.blue()))

        self.image().image = QtGui.QImage(pil_im.convert("RGB").tobytes("raw", "RGB"), pil_im.size[0], pil_im.size[1], QtGui.QImage.Format_RGB888)
        self.update()
Beispiel #41
0
def scale(image, width, height):
    edited = QImage.fromData(image.data, format_for(image.mime))
    if edited.isNull():
        return image

    scaled = edited.scaled(width, height, Qt.KeepAspectRatio, Qt.SmoothTransformation)

    buffer = QBuffer()
    buffer.open(QIODevice.WriteOnly)
    scaled.save(buffer, format_for(image.mime))
    buffer.close()
    return Image(mime=image.mime, data=buffer.data(), desc=image.desc, type_=image.type)
Beispiel #42
0
    def sendMessage(self):
        textbuf = QBuffer()
        textbuf.open(QBuffer.ReadWrite)
        messageText = QDataStream(textbuf)
        messageText << self.ui.messageBox.text
        size = textbuf.size()

        if not self.shareMemory.create(size):
            return

        size = min(self.shareMemory.size(), size)
        self.sharedMemory.lock()
Beispiel #43
0
def encode_jpeg(file_path, quality=80):
    from calibre.utils.speedups import ReadOnlyFileBuffer
    quality = max(0, min(100, int(quality)))
    exe = get_exe_path('cjpeg')
    cmd = [exe] + '-optimize -progressive -maxmemory 100M -quality'.split() + [str(quality)]
    img = QImage()
    if not img.load(file_path):
        raise ValueError('%s is not a valid image file' % file_path)
    ba = QByteArray()
    buf = QBuffer(ba)
    buf.open(QBuffer.WriteOnly)
    if not img.save(buf, 'PPM'):
        raise ValueError('Failed to export image to PPM')
    return run_optimizer(file_path, cmd, as_filter=True, input_data=ReadOnlyFileBuffer(ba.data()))
 def sendDeleteRequest(self, endpoint, data={}, params={}, headers={}):
     buff = QBuffer()
     buff.open(QBuffer.ReadWrite)
     d = json.dumps(data).encode('utf-8')
     buff.write(d)
     buff.seek(0)
     headers.update({"Content-Type":"application/json"})
     content = self.sendRequest( endpoint, params,
         'delete',
         buff,
         headers=headers
     )
     buff.close()
     return content
Beispiel #45
0
    def loadFromFile(self):
        """ This slot function is called when the "Load Image From File..."
        button is pressed on the firs Dialog process.  First, it tests whether
        the process is already connected to a shared memory segment and, if so,
        detaches from that segment.  This ensures that we always start the
        example from the beginning if we run it multiple times with the same
        two Dialog processes.  After detaching from an existing shared memory
        segment, the user is prompted to select an image file.  The selected
        file is loaded into a QImage.  The QImage is displayed in the Dialog
        and streamed into a QBuffer with a QDataStream.  Next, it gets a new
        shared memory segment from the system big enough to hold the image data
        in the QBuffer, and it locks the segment to prevent the second Dialog
        process from accessing it.  Then it copies the image from the QBuffer
        into the shared memory segment.  Finally, it unlocks the shared memory
        segment so the second Dialog process can access it.  After self
        function runs, the user is expected to press the "Load Image from
        Shared Memory" button on the second Dialog process.
        """

        if self.sharedMemory.isAttached():
            self.detach()

        self.ui.label.setText("Select an image file")
        fileName, _ = QFileDialog.getOpenFileName(self, None, None,
                "Images (*.png *.xpm *.jpg)")
        image = QImage()
        if not image.load(fileName):
            self.ui.label.setText(
                    "Selected file is not an image, please select another.")
            return

        self.ui.label.setPixmap(QPixmap.fromImage(image))

        # Load into shared memory.
        buf = QBuffer()
        buf.open(QBuffer.ReadWrite)
        out = QDataStream(buf)
        out << image
        size = buf.size()

        if not self.sharedMemory.create(size):
            self.ui.label.setText("Unable to create shared memory segment.")
            return

        size = min(self.sharedMemory.size(), size)
        self.sharedMemory.lock()

        # Copy image data from buf into shared memory area.
        self.sharedMemory.data()[:] = buf.data().data()
        self.sharedMemory.unlock()
    def perform_delete(self, endpoint, data, url):
        """
        Perform an HTTP DELETE request.

        :param endpoint: the name of the Tribler endpoint.
        :param data: the data/body to send with the request.
        :param url: the url to send the request to.
        """
        buf = QBuffer()
        buf.setData(data)
        buf.open(QIODevice.ReadOnly)
        delete_request = QNetworkRequest(QUrl(url))
        reply = self.sendCustomRequest(delete_request, "DELETE", buf)
        buf.setParent(reply)
        return reply
Beispiel #47
0
def fromqimage(im):
    buffer = QBuffer()
    buffer.open(QIODevice.ReadWrite)
    im.save(buffer, 'ppm')

    b = BytesIO()
    try:
        b.write(buffer.data())
    except TypeError:
        # workaround for Python 2
        b.write(str(buffer.data()))
    buffer.close()
    b.seek(0)

    return PIL.Image.open(b)
Beispiel #48
0
 def setImage(self, image):
     """
     Public method to set the image of the engine.
     
     @param image image to be set (QImage)
     """
     if not self._imageUrl:
         imageBuffer = QBuffer()
         imageBuffer.open(QIODevice.ReadWrite)
         if image.save(imageBuffer, "PNG"):
             self._imageUrl = "data:image/png;base64,{0}".format(
                 bytes(imageBuffer.buffer().toBase64()).decode())
     
     self.__image = QImage(image)
     self.imageChanged.emit()
 def capture(self, fullScreen = False, filename = ''):
     if fullScreen:
         image = QApplication.primaryScreen().grabWindow(0)
     else:
         image = QImage(self.webView.mainFrame.contentsSize(), QImage.Format_ARGB32)
         painter = QPainter(image)
         self.webView.mainFrame.render(painter)
         painter.end()
     if filename:
         return image.save(filename)
     else:
         data = QByteArray()
         buffer = QBuffer(data)
         buffer.open(QBuffer.WriteOnly)
         image.save(buffer, 'PNG')
         return bytes(data.toBase64()).decode()
Beispiel #50
0
    def createData(self, mimeType):
        if mimeType != 'image/png':
            return

        image = QImage(self.imageLabel.size(), QImage.Format_RGB32)
        painter = QPainter()
        painter.begin(image)
        self.imageLabel.renderer().render(painter)
        painter.end()

        data = QByteArray()
        buffer = QBuffer(data)
        buffer.open(QIODevice.WriteOnly)
        image.save(buffer, 'PNG')
        buffer.close()
        self.mimeData.setData('image/png', data)
Beispiel #51
0
 def __getitem__(key):
    if key not in IconCache.icons:
       if not key.endswith('.svg') and not key.endswith('.svgz'):
          image = QImage(key).scaled(24, 24)
       else:
          svg = QSvgRenderer(key)
          image = QImage(24, 24, QImage.Format_ARGB32)
          image.fill(0)
          painter = QPainter(image)
          svg.render(painter)
          painter.end()
       bytes = QByteArray()
       buff = QBuffer(bytes)
       buff.open(QIODevice.WriteOnly)
       image.save(buff, 'png')
       IconCache.icons[key] = bytes
    return QIcon(QPixmap.fromImage(QImage.fromData(IconCache.icons[key])))
    def _setNewImage(self, image):
        maxWidth = 16
        maxHeight = 16
        if image.width() > maxWidth or image.height() > maxHeight:
            scaledImage = image.scaled(maxWidth, maxHeight,
                    Qt.KeepAspectRatio, Qt.SmoothTransformation)
        else:
            scaledImage = image

        ba = QByteArray()
        buffer = QBuffer(ba)
        buffer.open(QIODevice.WriteOnly)
        scaledImage.save(buffer, 'png')

        model = self.model()
        index = model.index(self.selectedIndex().row(), model.sourceModel().fieldIndex('icon'))
        model.setData(index, ba)
    def requestStarted(self, job):
        """Handle a request for a qute: scheme.

        This method must be reimplemented by all custom URL scheme handlers.
        The request is asynchronous and does not need to be handled right away.

        Args:
            job: QWebEngineUrlRequestJob
        """
        url = job.requestUrl()
        assert job.requestMethod() == b'GET'
        assert url.scheme() == 'qute'
        log.misc.debug("Got request for {}".format(url.toDisplayString()))
        try:
            mimetype, data = qutescheme.data_for_url(url)
        except qutescheme.NoHandlerFound:
            log.misc.debug("No handler found for {}".format(
                url.toDisplayString()))
            job.fail(QWebEngineUrlRequestJob.UrlNotFound)
        except qutescheme.QuteSchemeOSError:
            # FIXME:qtwebengine how do we show a better error here?
            log.misc.exception("OSError while handling qute://* URL")
            job.fail(QWebEngineUrlRequestJob.UrlNotFound)
        except qutescheme.QuteSchemeError:
            # FIXME:qtwebengine how do we show a better error here?
            log.misc.exception("Error while handling qute://* URL")
            job.fail(QWebEngineUrlRequestJob.RequestFailed)
        except qutescheme.Redirect as e:
            qtutils.ensure_valid(e.url)
            job.redirect(e.url)
        else:
            log.misc.debug("Returning {} data".format(mimetype))

            # We can't just use the QBuffer constructor taking a QByteArray,
            # because that somehow segfaults...
            # https://www.riverbankcomputing.com/pipermail/pyqt/2016-September/038075.html
            buf = QBuffer(parent=self)
            buf.open(QIODevice.WriteOnly)
            buf.write(data)
            buf.seek(0)
            buf.close()
            job.reply(mimetype.encode('ascii'), buf)
Beispiel #54
0
def fromqimage(im):
    buffer = QBuffer()
    buffer.open(QIODevice.ReadWrite)
    # preserve alha channel with png
    # otherwise ppm is more friendly with Image.open
    if im.hasAlphaChannel():
        im.save(buffer, 'png')
    else:
        im.save(buffer, 'ppm')

    b = BytesIO()
    try:
        b.write(buffer.data())
    except TypeError:
        # workaround for Python 2
        b.write(str(buffer.data()))
    buffer.close()
    b.seek(0)

    return Image.open(b)
Beispiel #55
0
def image_to_data(img, compression_quality=95, fmt='JPEG', png_compression_level=9, jpeg_optimized=True, jpeg_progressive=False):
    '''
    Serialize image to bytestring in the specified format.

    :param compression_quality: is for JPEG and goes from 0 to 100. 100 being lowest compression, highest image quality
    :param png_compression_level: is for PNG and goes from 0-9. 9 being highest compression.
    :param jpeg_optimized: Turns on the 'optimize' option for libjpeg which losslessly reduce file size
    :param jpeg_progressive: Turns on the 'progressive scan' option for libjpeg which allows JPEG images to be downloaded in streaming fashion
    '''
    fmt = fmt.upper()
    ba = QByteArray()
    buf = QBuffer(ba)
    buf.open(QBuffer.WriteOnly)
    if fmt == 'GIF':
        w = QImageWriter(buf, b'PNG')
        w.setQuality(90)
        if not w.write(img):
            raise ValueError('Failed to export image as ' + fmt + ' with error: ' + w.errorString())
        from PIL import Image
        im = Image.open(BytesIO(ba.data()))
        buf = BytesIO()
        im.save(buf, 'gif')
        return buf.getvalue()
    is_jpeg = fmt in ('JPG', 'JPEG')
    w = QImageWriter(buf, fmt.encode('ascii'))
    if is_jpeg:
        if img.hasAlphaChannel():
            img = blend_image(img)
        # QImageWriter only gained the following options in Qt 5.5
        if jpeg_optimized:
            w.setOptimizedWrite(True)
        if jpeg_progressive:
            w.setProgressiveScanWrite(True)
        w.setQuality(compression_quality)
    elif fmt == 'PNG':
        cl = min(9, max(0, png_compression_level))
        w.setQuality(10 * (9-cl))
    if not w.write(img):
        raise ValueError('Failed to export image as ' + fmt + ' with error: ' + w.errorString())
    return ba.data()
Beispiel #56
0
 def open(self, _fname, mode):
     """Open an in-memory PyQIODevice instead of a real file."""
     modes = {
         'wb': QIODevice.WriteOnly | QIODevice.Truncate,
         'w': QIODevice.WriteOnly | QIODevice.Text | QIODevice.Truncate,
         'rb': QIODevice.ReadOnly,
         'r': QIODevice.ReadOnly | QIODevice.Text,
     }
     try:
         qt_mode = modes[mode]
     except KeyError:
         raise ValueError("Invalid mode {}!".format(mode))
     f = QBuffer(self._data)
     f.open(qt_mode)
     qiodev = qtutils.PyQIODevice(f)
     # Make sure tests using name/mode don't blow up.
     qiodev.name = test_file.TESTFN
     qiodev.mode = mode
     # Create empty TESTFN file because the Python tests try to unlink
     # it.after the test.
     open(test_file.TESTFN, 'w', encoding='utf-8').close()
     return qiodev
Beispiel #57
0
def fromqimage(im):
    """
    :param im: A PIL Image object, or a file name
    (given either as Python string or a PyQt string object)
    """
    buffer = QBuffer()
    buffer.open(QIODevice.ReadWrite)
    # preserve alha channel with png
    # otherwise ppm is more friendly with Image.open
    if im.hasAlphaChannel():
        im.save(buffer, 'png')
    else:
        im.save(buffer, 'ppm')

    b = BytesIO()
    try:
        b.write(buffer.data())
    except TypeError:
        # workaround for Python 2
        b.write(str(buffer.data()))
    buffer.close()
    b.seek(0)

    return Image.open(b)
Beispiel #58
0
    def write(self, stream, nodes, mode = MeshWriter.OutputMode.BinaryMode):
        archive = VirtualFile()
        archive.openStream(stream, "application/x-ufp", OpenMode.WriteOnly)

        #Store the g-code from the scene.
        archive.addContentType(extension = "gcode", mime_type = "text/x-gcode")
        gcode_textio = StringIO() #We have to convert the g-code into bytes.
        gcode_writer = cast(MeshWriter, PluginRegistry.getInstance().getPluginObject("GCodeWriter"))
        success = gcode_writer.write(gcode_textio, None)
        if not success: #Writing the g-code failed. Then I can also not write the gzipped g-code.
            self.setInformation(gcode_writer.getInformation())
            return False
        gcode = archive.getStream("/3D/model.gcode")
        gcode.write(gcode_textio.getvalue().encode("UTF-8"))
        archive.addRelation(virtual_path = "/3D/model.gcode", relation_type = "http://schemas.ultimaker.org/package/2018/relationships/gcode")

        self._createSnapshot()

        #Store the thumbnail.
        if self._snapshot:
            archive.addContentType(extension = "png", mime_type = "image/png")
            thumbnail = archive.getStream("/Metadata/thumbnail.png")

            thumbnail_buffer = QBuffer()
            thumbnail_buffer.open(QBuffer.ReadWrite)
            thumbnail_image = self._snapshot
            thumbnail_image.save(thumbnail_buffer, "PNG")

            thumbnail.write(thumbnail_buffer.data())
            archive.addRelation(virtual_path = "/Metadata/thumbnail.png", relation_type = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail", origin = "/3D/model.gcode")
        else:
            Logger.log("d", "Thumbnail not created, cannot save it")

        # Store the material.
        application = Application.getInstance()
        machine_manager = application.getMachineManager()
        material_manager = application.getMaterialManager()
        global_stack = machine_manager.activeMachine

        material_extension = "xml.fdm_material"
        material_mime_type = "application/x-ultimaker-material-profile"

        try:
            archive.addContentType(extension = material_extension, mime_type = material_mime_type)
        except:
            Logger.log("w", "The material extension: %s was already added", material_extension)

        added_materials = []
        for extruder_stack in global_stack.extruders.values():
            material = extruder_stack.material
            try:
                material_file_name = material.getMetaData()["base_file"] + ".xml.fdm_material"
            except KeyError:
                Logger.log("w", "Unable to get base_file for the material %s", material.getId())
                continue
            material_file_name = "/Materials/" + material_file_name

            # The same material should not be added again.
            if material_file_name in added_materials:
                continue

            material_root_id = material.getMetaDataEntry("base_file")
            material_group = material_manager.getMaterialGroup(material_root_id)
            if material_group is None:
                Logger.log("e", "Cannot find material container with root id [%s]", material_root_id)
                return False

            material_container = material_group.root_material_node.getContainer()
            try:
                serialized_material = material_container.serialize()
            except NotImplementedError:
                Logger.log("e", "Unable serialize material container with root id: %s", material_root_id)
                return False

            material_file = archive.getStream(material_file_name)
            material_file.write(serialized_material.encode("UTF-8"))
            archive.addRelation(virtual_path = material_file_name,
                                relation_type = "http://schemas.ultimaker.org/package/2018/relationships/material",
                                origin = "/3D/model.gcode")

            added_materials.append(material_file_name)

        archive.close()
        return True