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 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 #3
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 #4
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
 def read(self, fileName):
     uncompressed = QByteArray()
     # Read data
     f = QFile(fileName)
     if (f.open(QIODevice.ReadOnly)) :
         compressed = f.readAll()
         f.close()
         uncompressed, length = decompress(compressed, 48 * 48)
     
     # Check the data
     if (uncompressed.count() != 48 * 48) :
         self.mError = self.tr("This is not a valid Droidcraft map file!")
         return None
     
     uncompressed = uncompressed.data()
     # Build 48 x 48 map
     # Create a Map -> Create a Tileset -> Add Tileset to map
     # -> Create a TileLayer -> Fill layer -> Add TileLayer to Map
     map = Map(Map.Orientation.Orthogonal, 48, 48, 32, 32)
     mapTileset = Tileset.create("tileset", 32, 32)
     mapTileset.loadFromImage(QImage(":/tileset.png"), "tileset.png")
     map.addTileset(mapTileset)
     # Fill layer
     mapLayer =  TileLayer("map", 0, 0, 48, 48)
     # Load
     for i in range(0, 48 * 48):
         tileFile = int(uncompressed[i])&0xff
         y = int(i / 48)
         x = i - (48 * y)
         tile = mapTileset.tileAt(tileFile)
         mapLayer.setCell(x, y, Cell(tile))
     
     map.addLayer(mapLayer)
     return map
Beispiel #6
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 #7
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 #8
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 #9
0
def _decode(pixmap, format='jpg'):
    ba = QByteArray()
    buff = QBuffer(ba)
    buff.open(QIODevice.WriteOnly)
    ok = pixmap.save(buff, format)
    assert ok
    return ba.data()
Beispiel #10
0
    def read(self, fileName):
        uncompressed = QByteArray()
        # Read data
        f = QFile(fileName)
        if (f.open(QIODevice.ReadOnly)):
            compressed = f.readAll()
            f.close()
            uncompressed, length = decompress(compressed, 48 * 48)

        # Check the data
        if (uncompressed.count() != 48 * 48):
            self.mError = self.tr("This is not a valid Droidcraft map file!")
            return None

        uncompressed = uncompressed.data()
        # Build 48 x 48 map
        # Create a Map -> Create a Tileset -> Add Tileset to map
        # -> Create a TileLayer -> Fill layer -> Add TileLayer to Map
        map = Map(Map.Orientation.Orthogonal, 48, 48, 32, 32)
        mapTileset = Tileset.create("tileset", 32, 32)
        mapTileset.loadFromImage(QImage(":/tileset.png"), "tileset.png")
        map.addTileset(mapTileset)
        # Fill layer
        mapLayer = TileLayer("map", 0, 0, 48, 48)
        # Load
        for i in range(0, 48 * 48):
            tileFile = int(uncompressed[i]) & 0xff
            y = int(i / 48)
            x = i - (48 * y)
            tile = mapTileset.tileAt(tileFile)
            mapLayer.setCell(x, y, Cell(tile))

        map.addLayer(mapLayer)
        return map
Beispiel #11
0
    def copy_image(self, image, path):
        # TODO : fails if the directory does not exist
        # (which  indicates the transcode failed)

        src = self.parent.target_source

        if src.isGetPutSupported():

            ba = QByteArray()
            buf = QBuffer(ba)
            image.save(buf, "JPG")
            #buf.seek(0)
            fo = io.BytesIO(ba.data())
            print(path)

            try:
                src.putfo(path, fo)
            except Exception as e:
                print("Exception copying art:")
                print("from: %s" % path)
                print("to  : %s" % fo)
                print("%s" % e)

        else:
            print("copy not supported for album art")
Beispiel #12
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 #13
0
 def paste_on_clipboard(self, pixmap):
     ba = QByteArray()
     buff = QBuffer(ba)
     buff.open(QIODevice.WriteOnly)
     pixmap.save(buff, "bmp")
     pixmap_bytes = ba.data()
     self.set_clipboard_img(pixmap_bytes)
     print(len(pixmap_bytes))
Beispiel #14
0
    def sendOneImage(self):
        if not self.isImageLoaded:
            self.makeErrMessage("Зарузите избражение")

        #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()
        #marked image
        mmarked_img_bytes = QByteArray()
        marked_img_buff = QBuffer(mmarked_img_bytes)
        marked_img_buff.open(QIODevice.WriteOnly)
        marked_img = self.getMarkedImage()
        marked_img.save(marked_img_buff, extention)
        marked_img_buff.close()

        self.metafileobj.setPoints(self.pointsArray)

        payload = {
            'id': str(client_config['id']),
            'code': ReqCodes.NEW_IMAGES._value_,
            'count': 1,
            'data': [{
                'metafile': str(self.metafileobj.getDict()),
                'originalImage': str(base64.b64encode(original_img_bytes.data()), 'utf-8'),
                'markedImage': str(base64.b64encode(mmarked_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']).json()
            print(response)
        except:
            self.makeErrMessage("Произшала ошибка при взаимодействии с сервером, попробуйте позже")
        finally:
            del original_img_bytes
            del original_img_buff
            del marked_img
            del mmarked_img_bytes
            del marked_img_buff
            del json_data
Beispiel #15
0
def qtPixmapToJPG(pixmap):
    arr = QByteArray()
    b = QBuffer(arr)
    b.open(QIODevice.WriteOnly)

    if pixmap.save(b, "JPG"):
        return arr.data()
    return None
Beispiel #16
0
 def qImg2bytes(q_img):
     # 获取一个空的字节数组
     byte_array = QByteArray()
     # 将字节数组绑定到输出流上
     qImg_buffer = QBuffer(byte_array)
     qImg_buffer.open(QIODevice.WriteOnly)
     # 将数据使用jpg格式进行保存
     q_img.save(qImg_buffer, 'jpg', quality=32)  # 1-100
     return byte_array.data()
Beispiel #17
0
 def pixmap_to_bytes(pixmap: QPixmap) -> bytes:
     image = pixmap.toImage()
     grayed = image.convertToFormat(QImage.Format.Format_Grayscale8)
     ba = QByteArray()
     bf = QBuffer(ba)
     bf.open(QIODevice.WriteOnly)
     ok = grayed.save(bf, 'PNG')
     assert ok
     return ba.data()
Beispiel #18
0
 def _extract_image(cls, qmimedata):
     ba = QByteArray()
     buffer = QBuffer(ba)
     buffer.open(QIODevice.WriteOnly)
     image_data = qmimedata.imageData()
     if not image_data:
         raise ClipboardHadNoImageError(qmimedata)
     image_data.save(buffer, 'PNG')
     return ba.data()
    def __translate_image_text(self) -> None:
        """Requests OCR translation from self.translateDelegate, and triggers drawing of translation.
        """

        data = QByteArray()
        buffer = QBuffer(data)
        self.imageView.get_current_image().save(buffer, 'JPG')

        word_boxes = self.translateDelegate.translate_image_text(data.data())
        self.imageView.draw_word_boxes(word_boxes)
Beispiel #20
0
class ComPortClass(QObject):
    def __init__(self):

        self.SerialPort = QtSerialPort.QSerialPort()
        self.SerialPort.setBaudRate(115200)
        self.SerialPort.setPortName("COM8")
        self.SerialPort.readyRead.connect(self.ReadData)

        self.DATA_WAIT_SIZE = 0
        self.DATA_BUFFER = QByteArray()
        self.DATA_MESSAGE = QByteArray()
        self.FLAG_WAIT_DATA = False
    def OpenPort(self):
        result = self.SerialPort.open(QtSerialPort.QSerialPort.ReadWrite)
        print(" PORT - ",self.SerialPort.portName()," OPENED")


        #self.Window.ui.ButtonOpenPort.clicked.connect(self.OpenPort)
        #self.Window.ui.ButtonSendData.clicked.connect(self.TestCOMConnection)
        #self.Window.ui.ButStepMotorRight.clicked.connect(lambda: self.MotorControl.MoveStepMotor(NumberMotor=0,Direction=1))
        #self.Window.ui.ButStepMotorLeft.clicked.connect(lambda: self.MotorControl.MoveStepMotor(NumberMotor=1,Direction=-1))


    def TestCOMConnection(self):
        self.HEADER_DATA = bytearray.fromhex("A1 F1 00")
        COMMAND_HEADER = bytearray.fromhex("01")
        self.DATA = COMMAND_HEADER + bytearray("TEST MESSAGE","utf-8")
        self.HEADER_DATA[2] = len(self.DATA)
        result = self.SerialPort.write(self.HEADER_DATA)
        result = self.SerialPort.write(self.DATA)
        print("SEND MESSAGE - ",self.DATA)

    def ClosePort(self):
        result = self.SerialPort.close()

    def ReadData(self):
        New_Data = self.SerialPort.readAll()
        self.DATA_BUFFER.append(New_Data)
        #print("BUFFER -  " ,self.DATA_BUFFER.toHex(),"SIZE - ",self.DATA_BUFFER.length(),"WAIT - ",self.DATA_WAIT_SIZE)

        while(self.DATA_BUFFER.length() >= 3):

            if(self.DATA_BUFFER[0] == b'\xF1' and self.DATA_BUFFER[1] == b'\xA1'):
                self.DATA_WAIT_SIZE = self.DATA_BUFFER[2][0]
                self.DATA_BUFFER.remove(0,3)

            if(self.DATA_BUFFER.length() >= self.DATA_WAIT_SIZE):
                self.DATA_MESSAGE.clear()
                self.DATA_MESSAGE.append(self.DATA_BUFFER)
                self.DATA_BUFFER.remove(0,self.DATA_WAIT_SIZE)
                self.DATA_MESSAGE.truncate(self.DATA_WAIT_SIZE)
                print(self.DATA_BUFFER.toHex())
                self.Window.AddText("    " + self.DATA_MESSAGE.data().decode(encoding="utf-8"),0)
            else:
                break;
Beispiel #21
0
    async def save_image_to_db(self):
        ba = QByteArray()
        buff = QBuffer(ba)
        buff.open(QIODevice.WriteOnly)
        ok = self.pixmap.save(buff, "PNG")
        assert ok
        pixmap_bytes = ba.data()

        self.parent.parent.database.add_client_info(pixmap_bytes)

        await asyncio.sleep(1)
Beispiel #22
0
    def readData(self, maxlen):
        data = QByteArray()
        total = 0

        while maxlen > total:
            chunk = min(self.m_buffer.size() - self.m_pos, maxlen - total)
            data.append(self.m_buffer.mid(self.m_pos, chunk))
            self.m_pos = (self.m_pos + chunk) % self.m_buffer.size()
            total += chunk

        return data.data()
Beispiel #23
0
    def readData(self, maxlen):
        data = QByteArray()
        total = 0

        while maxlen > total:
            chunk = min(self.m_buffer.size() - self.m_pos, maxlen - total)
            data.append(self.m_buffer.mid(self.m_pos, chunk))
            self.m_pos = (self.m_pos + chunk) % self.m_buffer.size()
            total += chunk

        return data.data()
Beispiel #24
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 #25
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
Beispiel #26
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
Beispiel #27
0
class Buffer:

  def __init__(self):
    self._data = QByteArray()
    self.buf = QBuffer(self._data)
    self.buf.open(QIODevice.ReadWrite)
    # self.write = self.buf.write
    #TODO: use QTextStream

  def data(self):
    return self._data.data()

  def dataSize(self):
    return self._data.size()

  def write(self, data):
    self.buf.write(data.encode("utf-8") if type(data) == str else data)
Beispiel #28
0
 def getScreenAsData(self, quality = 20):
     ss = self.screen.grabWindow(self.sid);
     #b = ss.toImage().mirrored(True, True);
     #ss.convertFromImage(b);
     painter = QPainter();
     painter.begin(ss);
     painter.setBrush(QColor( 255,0,  0))
     size = 8;
     half_size = size / 2;
     cx, cy = self.getMouseXY();
     painter.drawEllipse(cx - half_size, cy - half_size, size,size);
     painter.end();
     #
     bytesArray = QByteArray();
     buff = QBuffer(bytesArray);
     ss.save(buff, 'JPEG', quality = quality)
     data = bytesArray.data();
     return data;
Beispiel #29
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() + [
        unicode_type(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()))
Beispiel #30
0
class IOController:
    def __init__(self, socket: QWebSocket):
        self.socket = socket
        self.motion_state = None
        self.state_changed = False

        self._curr_motion_state = QByteArray()
        self._last_motion_state = QByteArray()

        self.socket.binaryMessageReceived.connect(self.received_bytes)

    def received_bytes(self, qbytearray):
        self._curr_motion_state = qbytearray

    def get_new_motion_state(self):
        if self._curr_motion_state == self._last_motion_state:
            return None
        motion_state_array = array("d", self._curr_motion_state.data())
        return motion_state_array
Beispiel #31
0
def q_dumps(value, bits=32):
    def en_byte(v):
        if isinstance(v, str):
            return QByteArray(v.encode())
        elif isinstance(v, (bytes, bytearray)):
            return QByteArray(v)
        return v

    try:
        if isinstance(value, str):
            src = QVariant(QByteArray(value.encode()))
        elif isinstance(value, (bytes, bytearray)):
            src = QVariant(QByteArray(value))
        elif isinstance(value, (tuple, list)):
            src = QVariant([QVariant(en_byte(v)) for v in value])
        else:
            src = QVariant(value)
        dst = QByteArray()
        dll.dumps(sip.unwrapinstance(dst), sip.unwrapinstance(src), bits)
        # dll.dumps(shiboken2.getCppPointer(dst)[0], shiboken2.getCppPointer(src)[0])
        return dst.data()
    except Exception as e:
        print('q_dumps error:', e)
        raise ValueError
Beispiel #32
0
    def export_video(self):
        if not imageio:
            return QMessageBox(
                QMessageBox.Information, 'Export not available',
                'imageio and ffmpeg must be installed to export videos').exec(
                )

        location = QFileDialog.getSaveFileName(self,
                                               'Choose export location',
                                               filter='Video (*.mp4)')[0]
        if not location:
            return

        if not location.endswith('.mp4'):
            location += '.mp4'

        frame_count = int(self.duration * FPS)
        progress_box = QProgressDialog('Recording and exporting video...',
                                       'Cancel', 1, frame_count, self)
        progress_box.setWindowModality(Qt.WindowModal)
        with imageio.get_writer(location,
                                format='mp4',
                                mode='I',
                                fps=FPS,
                                quality=6) as writer:
            frame = 0
            stopped = False

            def new_event(*args):
                nonlocal frame, stopped
                try:
                    self.callback(
                        AniState(self,
                                 frame=frame,
                                 time=frame / FPS,
                                 dt=1 / FPS))
                    frame += 1
                except StopIteration:
                    stopped = True

            old = self.paintEvent
            self.paintEvent = new_event

            self.start()
            self.frame_no = 0
            for i in range(frame_count):
                progress_box.setValue(i)
                if progress_box.wasCanceled():
                    os.remove(location)
                    return

                im_bytes = QByteArray()
                buf = QBuffer(im_bytes)
                buf.open(QIODevice.WriteOnly)
                self.grab().save(buf, 'PNG', 100)  # Triggers paintEvent
                self.frame_no += 1
                writer.append_data(imageio.imread(im_bytes.data(), 'png'))
                if stopped:
                    break

        progress_box.setValue(progress_box.maximum())
        self.paintEvent = old

        return QMessageBox(
            QMessageBox.Information, 'Completed',
            'Export finished! Saved to {}'.format(location)).exec()
Beispiel #33
0
 def _decode_data(self, qba: QByteArray) -> str:
     """Decode data coming from a process."""
     encoding = locale.getpreferredencoding(do_setlocale=False)
     return qba.data().decode(encoding, 'replace')
Beispiel #34
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()))