예제 #1
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
예제 #2
0
    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)
예제 #3
0
 def opBuffer(self):
     memfile = QBuffer()  #创建内存文件
     memfile.open(QIODevice.WriteOnly)
     memfile.write(QByteArray(1024, "121121121121221222121221212"))
     memfile.write(QByteArray("787887878787878878787878778"))
     memfile.close()
     print(memfile.close())
예제 #4
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()
예제 #5
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
예제 #6
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()
예제 #7
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 
    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")
예제 #9
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
예제 #10
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
class ShareServiceInteractor:
    def __init__(self, view):
        self.view = view
        self.buffer = QBuffer()

        self.network_manager = QNetworkAccessManager(self.view)
        self.network_manager.finished.connect(self.on_received_response)

    def on_received_response(self, reply: QNetworkReply):
        if reply.error() != QNetworkReply.NoError:
            error_msg = "Unable to create new print share: {}".format(reply.errorString())
            logging.error(error_msg)
            app_settings.app_data_writer.signals.exchange_share_failed.emit(error_msg)
            return

        share_location = reply.rawHeader(QByteArray(bytes("Location", encoding="utf-8")))
        app_settings.app_data_writer.signals.exchange_share_created.emit(share_location.data().decode())
        reply.deleteLater()
        self.buffer.close()

    def create_document(self, raw_html):
        app_config = app_settings.load_configuration()
        url: QUrl = QUrl(app_config.print_server + "/prints")
        base64_encoded = str_to_base64_encoded_bytes(raw_html)
        jdoc = {"document": bytes_to_str(base64_encoded)}
        jdoc_str = json.dumps(jdoc)
        self.buffer.setData(str_to_bytes(jdoc_str))
        network_request = QNetworkRequest(url)
        network_request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")
        in_progress_reply = self.network_manager.post(network_request, self.buffer)
        self.view.finished.connect(in_progress_reply.abort)
예제 #12
0
 def createDocument(self):
     from . import poppler
     rect = self.autoCroppedRect()
     buf = QBuffer()
     buf.open(QBuffer.WriteOnly)
     success = self.page().pdf(buf, rect, self.resolution, self.paperColor)
     buf.close()
     return poppler.PopplerDocument(buf.data(), self.renderer())
예제 #13
0
 def export(self):
     rect = self.autoCroppedRect()
     buf = QBuffer()
     buf.open(QBuffer.WriteOnly)
     success = self.page().eps(buf, rect, self.resolution, self.paperColor)
     buf.close()
     if success:
         return buf.data()
예제 #14
0
def qimage_to_bytes(qimg: QImage) -> bytes:
    buffer = QBuffer()
    buffer.open(QBuffer.ReadWrite)
    try:
        qimg.save(buffer, 'jpg')
        return bytes(buffer.data())
    finally:
        buffer.close()
예제 #15
0
 def to_base64(self) -> bytes:
     """image in base64 encode format"""
     ba = QByteArray()
     bu = QBuffer(ba)
     bu.open(QBuffer.ReadWrite)
     self.save(bu, "PNG")
     imb_b64 = ba.toBase64().data()
     bu.close()
     return imb_b64
예제 #16
0
    def QImagetoPIL(self, qimage):
        buffer = QBuffer()
        buffer.open(QIODevice.ReadWrite)
        qimage.save(buffer, "PNG")

        byteio = io.BytesIO()
        byteio.write(buffer.data())
        buffer.close()
        byteio.seek(0)
        pil_im = Image.open(byteio)
        return pil_im
    def crear(self):
        # Obtener el nombre de usuario y la foto
        nombre = " ".join(self.editNombre.text().split()).title()
        foto = self.labelImagen.pixmap()
        numero_trabajador = " ".join(self.editNumero.text())
        tarjeta = " ".join(self.editTrarjeta.text())
        puesto = " ".join(self.editPuesto.text())
        emergencia = " ".join(self.editEmergencia.text())
        # comentarios = " ".join(self.textEdit.text())

        if foto:
            # Convertir la foto al tipo de dato adecuado
            bArray = QByteArray()
            bufer = QBuffer(bArray)
            bufer.open(QIODevice.WriteOnly)
            bufer.close()
            foto.save(bufer, "PNG")
        else:
            bArray = ""

        if nombre and bArray:
            # Establecer conexión con la base de datos
            conexion = sqlite3.connect("DB_USUARIOS.db")
            cursor = conexion.cursor()

            # Crear tabla, si no existe
            cursor.execute("CREATE TABLE IF NOT EXISTS Usuarios (NOMBRE TEXT, FOTO BLOB, NUMERO_TRA TEXT, TARJETA TEX, PUESTO TEXT, EMERGENCIA TEXT)")
            conexion.commit()

            # Verificar que el usuario no exista
            if cursor.execute("SELECT * FROM Usuarios WHERE NOMBRE = ?", (nombre,)).fetchone():
                QMessageBox.information(self, "Atencion", "El usuario {} ya existe".format(nombre), QMessageBox.Ok)
            else:
                # Guardar en la base de datos, el nombre de usuario y la foto
                cursor.execute("INSERT INTO Usuarios VALUES (?,?,?,?,?,?)", (nombre, bArray, numero_trabajador, tarjeta, puesto, emergencia))
                conexion.commit()

                self.labelImagen.clear()
                self.editNombre.clear()
                self.editNumero.clear()
                self.editTrarjeta.clear()
                self.editPuesto.clear()
                self.editEmergencia.clear()
                self.textEdit.clear()

                QMessageBox.information(self, "Usuario", "El Usuario se registro con exito", QMessageBox.Ok)

            # Cerrar la conexión con la base de datos
            conexion.close()

            self.editNombre.setFocus()
        else:
            self.editNombre.setFocus()
예제 #18
0
파일: tomarFoto.py 프로젝트: ykv001/PyQt5
    def procesarImagenCapturada(self, requestId, imagen):
        foto = QPixmap.fromImage(imagen)

        buffer = QBuffer(self.byteArrayFoto)
        buffer.open(QIODevice.WriteOnly)
        buffer.close()
        foto.save(buffer, "PNG")

        fotoEscalada = foto.scaled(self.labelFoto.size())

        self.labelFoto.setPixmap(fotoEscalada)
        self.mostrarImagenCapturada()
예제 #19
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)
예제 #20
0
def qpixmap_to_pil_image(pixmap):
    image = QImage(pixmap)
    buffer = QBuffer()
    buffer.open(QIODevice.ReadWrite)
    image.save(buffer, "PNG")

    strio = io.BytesIO()
    strio.write(buffer.data())
    buffer.close()
    strio.seek(0)
    byte_img = strio.read()
    data_bytes = io.BytesIO(byte_img)
    return Image.open(data_bytes)
예제 #21
0
 def _encodeSnapshot(self, snapshot):
     Logger.log("d", "Encoding thumbnail image...")
     try:
         thumbnail_buffer = QBuffer()
         thumbnail_buffer.open(QBuffer.ReadWrite)
         thumbnail_image = snapshot
         thumbnail_image.save(thumbnail_buffer, "PNG")
         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")
예제 #22
0
파일: client.py 프로젝트: tanonl/openuds
 def screenshot(self) -> typing.Any:
     '''
     On windows, an RDP session with minimized screen will render "black screen"
     So only when user is using RDP connection will return an "actual" screenshot
     '''
     pixmap: 'QPixmap' = self._qApp.primaryScreen().grabWindow(0)
     ba = QByteArray()
     buffer = QBuffer(ba)
     buffer.open(QIODevice.WriteOnly)
     pixmap.save(buffer, 'PNG')
     buffer.close()
     scrBase64 = bytes(ba.toBase64()).decode()
     logger.debug('Screenshot length: %s', len(scrBase64))
     return scrBase64  # 'result' of JSON will contain base64 of screen
예제 #23
0
def pixmapAsBase64Url(pixmap):
    try:
        data = QByteArray()
        buffer = QBuffer(data)
        buffer.open(QIODevice.WriteOnly)
        pixmap.save(buffer, 'PNG')
        buffer.close()

        avatarUrl = 'data:image/png;base64, {}'.format(
            bytes(buffer.data().toBase64()).decode())
    except Exception:
        return None
    else:
        return f'<img src="{avatarUrl}"></img>'
예제 #24
0
 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
예제 #25
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)
예제 #26
0
def jf_pixmap(
        x_fn,
        x_format='PNG'):  # Load image from file for using QPixmap in java
    fu_qba = QByteArray()
    fu_qbf = QBuffer(fu_qba)
    fu_qbf.open(QIODevice.WriteOnly)
    QPixmap(x_fn).save(fu_qbf, x_format)
    fu_qbf.close()
    fu_jbaos = CjByteArrayOutputStream()
    for bx2_it in fu_qba.data():
        fu_jbaos.write(bx2_it)
    del (fu_qba)
    fu_jbais = CjByteArrayInputStream(fu_jbaos.toByteArray())
    fu_jbaos.close()
    return fu_jbais
예제 #27
0
 def get_piclist_data_to_dict(self):
     for i in range(self.lst_pices.count()):
         try:
             item = self.lst_pices.item(i)
             icon = item.icon()
             if icon:
                 pixmap = icon.pixmap(icon.availableSizes()[0])
                 array = QByteArray()
                 buffer = QBuffer(array)
                 buffer.open(QIODevice.WriteOnly)
                 pixmap.save(buffer, 'JPG')
                 buffer.close()
                 yield array.data()
         except Exception:
             pass
예제 #28
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)
예제 #29
0
    def ReadText(self):
        '''The handwriting to text function'''
        # Dark magic is required to convert the Canvas path into png format
        buffer = QBuffer()
        buffer.open(QIODevice.ReadWrite)
        self.canvas.image.save(buffer, "png")
        data = BytesIO(buffer.data())
        buffer.close()

        img = Image.open(data)  # Make a PIL image object from the png data
        img = PIL.ImageOps.invert(img)
        thresh = 200
        fn = lambda x: 255 if x > thresh else 0
        img = img.convert('L').point(
            fn,
            mode='1')  # Turns the image black and white (better for tesseract)

        # Code that crops the image so that the text fills the picture (also better for tesseract)
        colour = (0, 0, 0)  # (black)
        x_elements = []
        y_elements = []

        rgb_img = img.convert('RGB')
        for x in range(rgb_img.size[0]):
            for y in range(rgb_img.size[1]):
                r, g, b = rgb_img.getpixel((x, y))
                if (r, g, b) == colour:
                    x_elements.append(x)
                    y_elements.append(y)

        # +/-20px gives a nice border round the text
        x3 = min(x_elements) - 20
        y3 = min(y_elements) - 20
        x4 = max(x_elements) + 20
        y4 = max(y_elements) + 20
        crop = img.crop((x3, y3, x4, y4))

        # pytessesract calls tesseceract through the commandine
        text = pytesseract.image_to_string(
            crop, config='--psm 10'
        )  # TODO config is important so tweak for best performance
        text = text.replace(
            control, ""
        )  # If the control character appears, get rid of them! It will mess up saving/backspace

        # Add the text to the text editor and reset the canvas
        self.pages[self.display.currentIndex()].insertPlainText(text.strip())
        self.canvas.clearImage()
예제 #30
0
    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() == 'chrome-error':
            # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-63378
            job.fail(QWebEngineUrlRequestJob.UrlInvalid)
            return

        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)
예제 #31
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)
예제 #32
0
    def ReadText(self):
        buffer = QBuffer()
        buffer.open(QIODevice.ReadWrite)
        self.canvas.image.save(buffer, "PNG")
        data = BytesIO(buffer.data())
        buffer.close()

        img = Image.open(data)
        thresh = 200
        fn = lambda x: 255 if x > thresh else 0
        mod = img.convert('L').point(fn, mode='1')

        text = pytesseract.image_to_string(mod, config='--psm 10')
        text = text.replace("~|", "")
        self.pages[self.display.currentIndex()].insertPlainText(text.strip())
        self.canvas.clearImage()
예제 #33
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)
예제 #34
0
def qimage_to_pil_image(image):
    buffer = QBuffer()

    buffer.open(QIODevice.ReadWrite)

    image.save(buffer, "PNG")

    bytesio = BytesIO()
    bytesio.write(buffer.data())

    buffer.close()

    bytesio.seek(0)

    pil_image = Image.open(bytesio)

    return pil_image
예제 #35
0
    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)
예제 #36
0
파일: ImageQt.py 프로젝트: 2070616d/TP3
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)
예제 #37
0
파일: ImageQt.py 프로젝트: Ashaba/rms
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)
예제 #38
0
class HexEditChunks(object):
    """
    Class implementing the storage backend for the hex editor.
    
    When HexEditWidget loads data, HexEditChunks access them using a QIODevice
    interface. When the app uses a QByteArray or Python bytearray interface,
    QBuffer is used to provide again a QIODevice like interface. No data will
    be changed, therefore HexEditChunks opens the QIODevice in
    QIODevice.ReadOnly mode. After every access HexEditChunks closes the
    QIODevice. That's why external applications can overwrite files while
    HexEditWidget shows them.

    When the the user starts to edit the data, HexEditChunks creates a local
    copy of a chunk of data (4 kilobytes) and notes all changes there. Parallel
    to that chunk, there is a second chunk, which keeps track of which bytes
    are changed and which are not.
    """
    BUFFER_SIZE = 0x10000
    CHUNK_SIZE = 0x1000
    READ_CHUNK_MASK = 0xfffffffffffff000
    
    def __init__(self, ioDevice=None):
        """
        Constructor
        
        @param ioDevice io device to get the data from
        @type QIODevice
        """
        self.__ioDevice = None
        self.__pos = 0
        self.__size = 0
        self.__chunks = []
        
        if ioDevice is None:
            buf = QBuffer()
            self.setIODevice(buf)
        else:
            self.setIODevice(ioDevice)
    
    def setIODevice(self, ioDevice):
        """
        Public method to set an io device to read the binary data from.
        
        @param ioDevice io device to get the data from
        @type QIODevice
        @return flag indicating successful operation
        @rtype bool
        """
        self.__ioDevice = ioDevice
        ok = self.__ioDevice.open(QIODevice.ReadOnly)
        if ok:
            # open successfully
            self.__size = self.__ioDevice.size()
            self.__ioDevice.close()
        else:
            # fallback is an empty buffer
            self.__ioDevice = QBuffer()
            self.__size = 0
        
        self.__chunks = []
        self.__pos = 0
        
        return ok
    
    def data(self, pos=0, maxSize=-1, highlighted=None):
        """
        Public method to get data out of the chunks.
        
        @param pos position to get bytes from
        @type int
        @param maxSize maximum amount of bytes to get
        @type int
        @param highlighted reference to a byte array storing highlighting info
        @type bytearray
        @return retrieved data
        @rtype bytearray
        """
        ioDelta = 0
        chunkIdx = 0
        
        chunk = HexEditChunk()
        buffer = bytearray()
        
        if highlighted is not None:
            del highlighted[:]
        
        if pos >= self.__size:
            return buffer
        
        if maxSize < 0:
            maxSize = self.__size
        elif (pos + maxSize) > self.__size:
            maxSize = self.__size - pos
        
        self.__ioDevice.open(QIODevice.ReadOnly)
        
        while maxSize > 0:
            chunk.absPos = sys.maxsize
            chunksLoopOngoing = True
            while chunkIdx < len(self.__chunks) and chunksLoopOngoing:
                # In this section, we track changes before our required data
                # and we take the edited data, if availible. ioDelta is a
                # difference counter to justify the read pointer to the
                # original data, if data in between was deleted or inserted.
                
                chunk = self.__chunks[chunkIdx]
                if chunk.absPos > pos:
                    chunksLoopOngoing = False
                else:
                    chunkIdx += 1
                    chunkOfs = pos - chunk.absPos
                    if maxSize > (len(chunk.data) - chunkOfs):
                        count = len(chunk.data) - chunkOfs
                        ioDelta += self.CHUNK_SIZE - len(chunk.data)
                    else:
                        count = maxSize
                    if count > 0:
                        buffer += chunk.data[chunkOfs:chunkOfs + count]
                        maxSize -= count
                        pos += count
                        if highlighted is not None:
                            highlighted += \
                                chunk.dataChanged[chunkOfs:chunkOfs + count]
            
            if maxSize > 0 and pos < chunk.absPos:
                # In this section, we read data from the original source. This
                # will only happen, when no copied data is available.
                if chunk.absPos - pos > maxSize:
                    byteCount = maxSize
                else:
                    byteCount = chunk.absPos - pos
                
                maxSize -= byteCount
                self.__ioDevice.seek(pos + ioDelta)
                readBuffer = bytearray(self.__ioDevice.read(byteCount))
                buffer += readBuffer
                if highlighted is not None:
                    highlighted += bytearray(len(readBuffer))
                pos += len(readBuffer)
        
        self.__ioDevice.close()
        return buffer
    
    def write(self, ioDevice, pos=0, count=-1):
        """
        Public method to write data to an io device.
        
        @param ioDevice io device to write the data to
        @type QIODevice
        @param pos position to write bytes from
        @type int
        @param count amount of bytes to write
        @type int
        @return flag indicating success
        @rtype bool
        """
        if count == -1:
            # write all data
            count = self.__size
        
        ok = ioDevice.open(QIODevice.WriteOnly)
        if ok:
            idx = pos
            while idx < count:
                data = self.data(idx, self.BUFFER_SIZE)
                ioDevice.write(QByteArray(data))
                
                # increment loop variable
                idx += self.BUFFER_SIZE
            
            ioDevice.close()
        
        return ok
    
    def setDataChanged(self, pos, dataChanged):
        """
        Public method to set highlighting info.
        
        @param pos position to set highlighting info for
        @type int
        @param dataChanged flag indicating changed data
        @type bool
        """
        if pos < 0 or pos >= self.__size:
            # position is out of range, do nothing
            return
        chunkIdx = self.__getChunkIndex(pos)
        posInChunk = pos - self.__chunks[chunkIdx].absPos
        self.__chunks[chunkIdx].dataChanged[posInChunk] = int(dataChanged)
    
    def dataChanged(self, pos):
        """
        Public method to test, if some data was changed.
        
        @param pos byte position to check
        @type int
        @return flag indicating the changed state
        @rtype bool
        """
        highlighted = bytearray()
        self.data(pos, 1, highlighted)
        return highlighted and bool(highlighted[0])
    
    def indexOf(self, byteArray, start):
        """
        Public method to search the first occurrence of some data.
        
        @param byteArray data to search for
        @type bytearray
        @param start position to start the search at
        @type int
        @return position the data was found at or -1 if nothing could be found
        @rtype int
        """
        ba = bytearray(byteArray)
        
        result = -1
        pos = start
        while pos < self.__size:
            buffer = self.data(pos, self.BUFFER_SIZE + len(ba) - 1)
            findPos = buffer.find(ba)
            if findPos >= 0:
                result = pos + findPos
                break
            
            # increment loop variable
            pos += self.BUFFER_SIZE
        
        return result
    
    def lastIndexOf(self, byteArray, start):
        """
        Public method to search the last occurrence of some data.
        
        @param byteArray data to search for
        @type bytearray
        @param start position to start the search at
        @type int
        @return position the data was found at or -1 if nothing could be found
        @rtype int
        """
        ba = bytearray(byteArray)
        
        result = -1
        pos = start
        while pos > 0 and result < 0:
            sPos = pos - self.BUFFER_SIZE - len(ba) + 1
            if sPos < 0:
                sPos = 0
            
            buffer = self.data(sPos, pos - sPos)
            findPos = buffer.rfind(ba)
            if findPos >= 0:
                result = sPos + findPos
                break
            
            # increment loop variable
            pos -= self.BUFFER_SIZE
        
        return result
    
    def insert(self, pos, data):
        """
        Public method to insert a byte.
        
        @param pos position to insert at
        @type int
        @param data byte to insert
        @type int (range 0 to 255)
        @return flag indicating success
        @rtype bool
        """
        if pos < 0 or pos > self.__size:
            # position is out of range, do nothing
            return False
        
        if pos == self.__size:
            chunkIdx = self.__getChunkIndex(pos - 1)
        else:
            chunkIdx = self.__getChunkIndex(pos)
        chunk = self.__chunks[chunkIdx]
        posInChunk = pos - chunk.absPos
        chunk.data.insert(posInChunk, data)
        chunk.dataChanged.insert(posInChunk, 1)
        for idx in range(chunkIdx + 1, len(self.__chunks)):
            self.__chunks[idx].absPos += 1
        self.__size += 1
        self.__pos = pos
        return True
    
    def overwrite(self, pos, data):
        """
        Public method to overwrite a byte.
        
        @param pos position to overwrite
        @type int
        @param data byte to overwrite with
        @type int (range 0 to 255)
        @return flag indicating success
        @rtype bool
        """
        if pos < 0 or pos >= self.__size:
            # position is out of range, do nothing
            return False
        
        chunkIdx = self.__getChunkIndex(pos)
        chunk = self.__chunks[chunkIdx]
        posInChunk = pos - chunk.absPos
        chunk.data[posInChunk] = data
        chunk.dataChanged[posInChunk] = 1
        self.__pos = pos
        return True
    
    def removeAt(self, pos):
        """
        Public method to remove a byte.
        
        @param pos position to remove
        @type int
        @return flag indicating success
        @rtype bool
        """
        if pos < 0 or pos >= self.__size:
            # position is out of range, do nothing
            return
        
        chunkIdx = self.__getChunkIndex(pos)
        chunk = self.__chunks[chunkIdx]
        posInChunk = pos - chunk.absPos
        chunk.data.pop(posInChunk)
        chunk.dataChanged.pop(posInChunk)
        for idx in range(chunkIdx + 1, len(self.__chunks)):
            self.__chunks[idx].absPos -= 1
        self.__size -= 1
        self.__pos = pos
        return True
    
    def __getitem__(self, pos):
        """
        Special method to get a byte at a position.
        
        Note: This realizes the [] get operator.
        
        @param pos position of byte to get
        @type int
        @return requested byte
        @rtype int (range 0 to 255)
        """
        if pos >= self.__size:
            return 0
##            raise IndexError
        
        return self.data(pos, 1)[0]
    
    def pos(self):
        """
        Public method to get the current position.
        
        @return current position
        @rtype int
        """
        return self.__pos
    
    def size(self):
        """
        Public method to get the current data size.
        
        @return current data size
        @rtype int
        """
        return self.__size
    
    def __getChunkIndex(self, absPos):
        """
        Private method to get the chunk index for a position.
        
        This method checks, if there is already a copied chunk available. If
        there is one, it returns its index. If there is no copied chunk
        available, original data will be copied into a new chunk.
        
        @param absPos absolute position of the data.
        @type int
        @return index of the chunk containing the position
        @rtype int
        """
        foundIdx = -1
        insertIdx = 0
        ioDelta = 0
        
        for idx in range(len(self.__chunks)):
            chunk = self.__chunks[idx]
            if absPos >= chunk.absPos and \
                    absPos < (chunk.absPos + len(chunk.data)):
                foundIdx = idx
                break
            
            if absPos < chunk.absPos:
                insertIdx = idx
                break
            
            ioDelta += len(chunk.data) - self.CHUNK_SIZE
            insertIdx = idx + 1
        
        if foundIdx == -1:
            newChunk = HexEditChunk()
            readAbsPos = absPos - ioDelta
            readPos = readAbsPos & self.READ_CHUNK_MASK
            self.__ioDevice.open(QIODevice.ReadOnly)
            self.__ioDevice.seek(readPos)
            newChunk.data = bytearray(self.__ioDevice.read(self.CHUNK_SIZE))
            self.__ioDevice.close()
            newChunk.absPos = absPos - (readAbsPos - readPos)
            newChunk.dataChanged = bytearray(len(newChunk.data))
            self.__chunks.insert(insertIdx, newChunk)
            foundIdx = insertIdx
        
        return foundIdx