def createNullImage(self): nullImage = QtGui.QImage() byteArray = QtCore.QByteArray() buffer = QtCore.QBuffer(byteArray) buffer.open(QtCore.QIODevice.WriteOnly) nullImage.save(buffer, "PNG") return byteArray
def setAutolevel(self): xgmax = 0 xgmin = 255 image = self.imageName buffer = QtCore.QBuffer() buffer.open(QtCore.QBuffer.ReadWrite) image.save(buffer, "JPG") pil_im = Image.open(io.BytesIO(buffer.data())) pil_im.convert('RGB') width, height = pil_im.size for i in range(width): for j in range(height): r, g, b, a = QtGui.QColor(image.pixel(i ,j)).getRgb() xg = r if xg < xgmin: xgmin = xg if xg > xgmax: xgmax = xg for i in range(width): for j in range(height): r, g, b, a = QtGui.QColor(image.pixel(i ,j)).getRgb() xg = r xb = (255 * (xg - xgmin))/(xgmax-xgmin) image.setPixel(i, j, QtGui.QColor(xb, xb, xb, a).rgb()) self.showImage(QtGui.QPixmap.fromImage(image))
def widget_to_png_to_bytes(widget, keep_aspect=True, width=200, height=100): """ Renders the widget content in a png format as a bytes string Parameters ---------- widget: (QWidget) the widget to render keep_aspect: (bool) if True use width and the widget aspect ratio to calculate the height if False use set values of width and height to produce the png width: (int) the rendered width of the png height: (int) the rendered width of the png Returns ------- binary string """ png = widget.grab().toImage() wwidth = widget.width() wheight = widget.height() if keep_aspect: height = width * wheight / wwidth png = png.scaled(width, height, QtCore.Qt.KeepAspectRatio) buffer = QtCore.QBuffer() buffer.open(QtCore.QIODevice.WriteOnly) png.save(buffer, "png") return buffer.data().data()
def processImage(img): buffer = QtCore.QBuffer() buffer.open(QtCore.QBuffer.ReadWrite) img.save(buffer, "PNG") pil_img = Image.open(io.BytesIO(buffer.data())) buffer.close() try: result = pytesseract.image_to_string( pil_img, timeout=5, lang=(sys.argv[1] if len(sys.argv) > 1 else None)).strip() except RuntimeError as error: print( f"ERROR: An error occurred when trying to process the image: {error}" ) notify(f"An error occurred when trying to process the image: {error}") return if result: pyperclip.copy(result) print(f'INFO: Copied "{result}" to the clipboard') notify(f'Copied "{result}" to the clipboard') else: print(f"INFO: Unable to read text from image, did not copy") notify(f"Unable to read text from image, did not copy")
def display_popup(msg): global window def close_msg(): popup.destroy() window.setWindowIcon(QIcon('icon.png')) rand_exercise = exercise_controlelr.recommend_exercise() window.setWindowTitle('Your Exercise Recommendation Is:') window.setGeometry(100, 100, 600, 600) window.move(60, 15) main_layout = QVBoxLayout() exercise_header = parse_header(rand_exercise) header_label = QLabel(exercise_header) header_label.move(60, 15) main_layout.addWidget(header_label) img_urls = [ x.group() for x in re.finditer(r'<img id=".*" src=".*/>', rand_exercise, re.M) ] img_urls = [re.search(r'src="(.+?)"', url).group(1) for url in img_urls] movies_data = [] data_buffers = [] movies = [] movie_labels = [] gif_layout = QHBoxLayout() gif_layout.addStretch(1) for i in range(len(img_urls)): print(img_urls[i]) req = Request(img_urls[i], headers={'User-Agent': 'Mozilla/5.0'}) data = urlopen(req).read() movies_data.append(QtCore.QByteArray(data)) data_buffers.append(QtCore.QBuffer(movies_data[i])) data_buffers[i].open(QtCore.QIODevice.ReadOnly) movies.append(QMovie()) movies[i].setDevice(data_buffers[i]) movies[i].setFormat(QtCore.QByteArray(b'gif')) movie_labels.append(QLabel()) movie_labels[i].setMovie(movies[i]) gif_layout.addWidget(movie_labels[i]) movies[i].start() gif_layout.addStretch(1) main_layout.addLayout(gif_layout) exercise_instructions = parse_instructions(rand_exercise) instructions_label = QLabel(exercise_instructions) instructions_label.move(60, 15) main_layout.addWidget(instructions_label) window.setLayout(main_layout) window.show() app.exec_()
def getBytesFromPixmap(self, pixmap): ba = QtCore.QByteArray() buff = QtCore.QBuffer(ba) buff.open(QtCore.QIODevice.WriteOnly) ok = pixmap.save(buff, "PNG") assert ok pixmap_bytes = ba.data() return self.toNumpyBytes(pixmap_bytes)
def kuantisasi64(self): image = self.imageName buffer = QtCore.QBuffer() buffer.open(QtCore.QBuffer.ReadWrite) image.save(buffer, "JPG") pil_im = Image.open(io.BytesIO(buffer.data())) im = pil_im.convert("P", palette=Image.ADAPTIVE, colors=64) self.showImage(self.pil2pixmap(im))
def html(pixmap, attributes=''): """Return an <img>-tag that contains the pixmap embedded into HTML using a data-URI (https://en.wikipedia.org/wiki/Data_URI_scheme). Use this to include pixmaps that are not stored in a file into HTML-code. *attributes* is inserted into the tag and may contain arbitrary HTML-attributes. """ buffer = QtCore.QBuffer() pixmap.save(buffer, "PNG") string = bytes(buffer.buffer().toBase64()).decode('ascii') return '<img {} src="data:image/png;base64,{}" />'.format(attributes, string)
def request( self, request_header: QHttpRequestHeader, data_: Optional[Union[QtCore.QIODevice, QtCore.QByteArray]] = None, buffer_: Optional[QtCore.QBuffer] = None, ) -> None: """Send request.""" self._data = None del self._data if buffer_ is None: buffer_ = QtCore.QBuffer() _request = QtNetwork.QNetworkRequest() _tipo = request_header.method().lower() # if request_header.hasContentType(): # _request.setHeader( # QtNetwork.QNetworkRequest.ContentTypeHeader, request_header.contentType() # ) url_ = QtCore.QUrl(request_header.path()) for k in request_header._values.keys(): if k != "host": _request.setRawHeader( str.encode(k), str.encode(str(request_header._values[k]).lower())) else: url_ = QtCore.QUrl( "%s/%s" % (request_header.value("host"), request_header.path())) if not url_.isValid(): raise Exception("url_ is not a valid URL!") _request.setUrl(url_) method_ = getattr(self._manager, _tipo, None) self._data = buffer_ if self._data is not None: self._data.open(QtCore.QIODevice.ReadWrite) self._state = self.Connecting if _tipo == "get": self._reply = method_(_request) else: self._reply = method_(_request, data_) cast(QtCore.pyqtSignal, self._reply.downloadProgress).connect( self._slotNetworkProgressRead) cast(QtCore.pyqtSignal, self._reply.uploadProgress).connect(self._slotNetworkProgressSend) self._state = self.Connected self._current_id = request_header._id self.requestStarted.emit(request_header._id)
def get_bytes_from_pixmap(pix: QPixmap): if isinstance(pix, QPixmap): barray = QtCore.QByteArray() buff = QtCore.QBuffer(barray) buff.open(QtCore.QIODevice.WriteOnly) ok = pix.save(buff, "png") return barray.data() if ok else None else: return None
def create_qmovie(self): self.giffy = self.create_anim_gif(imageio.RETURN_BYTES) print('giffy=%d' %(len(self.giffy))) self.byteArray = QtCore.QByteArray(self.giffy) self.gif_bytes = QtCore.QBuffer(self.byteArray) # parent class is QIODevice # oh my, the second arg has to be bytes, but it is just the format name! # https://stackoverflow.com/questions/51832829/qmovie-unexpected-argument-qbuffer self.mov = QtGui.QMovie(self.gif_bytes, b"gif") return self.mov
def convertImage(fileName): ba = QtCore.QByteArray() buffer = QtCore.QBuffer(ba) buffer.open(QtCore.QIODevice.WriteOnly) image = QtGui.QImage(fileName) image.save(buffer, 'png') return ba
def qImageToImageio(qimage): """ Convert a QImage to an imageio image. """ buffer = QtCore.QBuffer() buffer.open(QtCore.QIODevice.ReadWrite) qimage.save(buffer, 'PNG') return imageio.imread(bytes(buffer.data()))
def grayscale(self): image = self.imageName buffer = QtCore.QBuffer() buffer.open(QtCore.QBuffer.ReadWrite) image.save(buffer, "JPG") pil_im = Image.open(io.BytesIO(buffer.data())) im = pil_im.convert('RGB') matrix = (0.2, 0.5, 0.3, 0.0, 0.2, 0.5, 0.3, 0.0, 0.2, 0.5, 0.3, 0.0) result = im.convert('RGB', matrix) self.showImage(self.pil2pixmap(result))
def qimage_to_pil_image(self, image): buffer = QtCore.QBuffer() buffer.open(QtCore.QIODevice.ReadWrite) image.save(buffer, "PNG") strio = io.BytesIO() strio.write(buffer.data()) buffer.close() strio.seek(0) return Image.open(strio)
def processImage(self, img): buffer = QtCore.QBuffer() buffer.open(QtCore.QBuffer.ReadWrite) img.save(buffer, "PNG") img_work = Image.open(io.BytesIO(buffer.data())) # Upscale new_size = (dim * 5 for dim in img_work.size) img_work = img_work.resize(new_size, resample=Image.LANCZOS) # Threshold img_work = np.array(img_work) img_work = skimage.color.rgb2gray(img_work) thresh = threshold_otsu(img_work) # thresh = threshold_yen(img_work) img_work = img_work > thresh # Final image img_final = Image.fromarray(img_work) # img2tex # img_final.save("temp.png") # buffer.close() # img2tex # result = ScribbleMyScience.img2tex("temp.png") # os.remove("temp.png") # if result: # result = result.strip() # result = "$$\n" + result + "\n$$\n" # else: try: result = pytesseract.image_to_string( img_final, timeout=20, lang=(sys.argv[1] if len(sys.argv) > 1 else None)) if result: result = result.strip() except RuntimeError as error: print( f"ERROR: An error occurred when trying to process the image: {error}" ) result = None if result: if result != "": pyperclip.copy(result) else: pyperclip.copy("OCR_FAILED") print(f"OCR_FAILED") else: pyperclip.copy("OCR_FAILED") print(f"OCR_FAILED")
def Kuantisasi64(self): image = self.imageName buffer = QtCore.QBuffer() buffer.open(QtCore.QBuffer.ReadWrite) image.save(buffer, "JPG") pil_im = Image.open(io.BytesIO(buffer.data())) im = pil_im.convert("P", palette=Image.ADAPTIVE, colors=64) self.scene = QtWidgets.QGraphicsScene() self.scene.addPixmap(self.pil2pixmap(im)) self.graphicsView_2.setScene(self.scene) self.graphicsView_2.fitInView(self.scene.itemsBoundingRect())
def onImageReady(self, filename, image): self.processedImages[self.filenames.index(filename)] = image remaining = len(self.filenames) - self.current_index if len(self.processedImages) == min(3, remaining): index_list = list(self.processedImages.keys()) index_list.sort() #here save images as pdf for index in index_list: image = self.processedImages[index] rotation = self.tableWidget.item(index, 0).rotation # create buffer for saving image in memory buff = QtCore.QBuffer(self) buff.open(QtCore.QIODevice.ReadWrite) img = PdfObj(Type='/XObject', Subtype='/Image', Width=image.width(), Height=image.height()) if self.clearBgBtn.isChecked( ): # Embed as monochrome png image #image = image.convertToFormat(QImage.Format_Mono) image.save(buff, "PNG") idat, palette, bpc = parse_png(buff.data().data()) #img['ColorSpace'] = '/DeviceGray' img['Filter'] = '/FlateDecode' img['BitsPerComponent'] = bpc img['ColorSpace'] = '[/Indexed /DeviceRGB 1 <ffffff000000>]' decode_parms = PdfDict(BitsPerComponent=bpc, Predictor=15, Colors=1, Columns=image.width()) img['DecodeParms'] = decode_parms imgdat = idat else: # embed as jpeg image img['ColorSpace'] = '/DeviceRGB' img['BitsPerComponent'] = 8 img['Filter'] = '/DCTDecode' image.save(buff, "JPG") imgdat = buff.data().data() self.writer.addObj(img, stream=imgdat) cont = PdfObj() pg_w, pg_h, matrix = pageMatrix(image.width(), image.height(), rotation) cont_strm = 'q %s /img0 Do Q' % matrix self.writer.addObj(cont, stream=cont_strm) page = self.writer.createPage(w=pg_w, h=pg_h, Contents=cont) page['Resources'] = PdfDict(XObject=PdfDict(img0=img)) self.writer.addPage(page) buff.data().clear() # clear buffer to free memory buff.close() self.processedImages.clear() self.current_index += min(3, remaining) self.beginProcessing()
def resize_image(cover_image): cover_image = cover_image.scaled(420, 600, QtCore.Qt.IgnoreAspectRatio) byte_array = QtCore.QByteArray() buffer = QtCore.QBuffer(byte_array) buffer.open(QtCore.QIODevice.WriteOnly) cover_image.save(buffer, 'jpg', 75) cover_image_final = io.BytesIO(byte_array) cover_image_final.seek(0) return cover_image_final.getvalue()
def take_screenshot(self): qPixmap = self.grab(QRect(QPoint(0, 0), QSize(-1, -1))) qImage = qPixmap.toImage() qBuffer = QtCore.QBuffer() qBuffer.open(QtCore.QIODevice.ReadWrite) qImage.save(qBuffer, "PNG") strio = BytesIO() strio.write(qBuffer.data()) qBuffer.close() strio.seek(0) pil_im = Image.open(strio) self.images.append(pil_im)
def qimage2base64(img, format): """ 将QImage对象转为base64字符串 :param img: QImage对象 :param format: 图片要转换为的格式:"PNG", "JPG" ...... :return: 转换后的字符串 """ data = QtCore.QByteArray() buf = QtCore.QBuffer(data) img.save(buf, format) s = bytes(data.toBase64()) return s
def get_zip_graphic(self, name): if os.path.exists("ecu.zip"): zf = zipfile.ZipFile("ecu.zip", "r") zname = "graphics/" + name + ".gif" if not zname in zf.namelist(): zname = "graphics/" + name + ".GIF" if zname in zf.namelist(): ba = core.QByteArray(zf.read(zname)) self.buffer = core.QBuffer() self.buffer.setData(ba) self.buffer.open(core.QIODevice.ReadOnly) self.img = gui.QMovie(self.buffer, b"gif")
def onFrameChanged(self, frame): if frame != 0: self.label_time.setNum(frame) else: self.label_time.setText("Smile...!") QtWidgets.QApplication.beep() image = QtGui.QImage(self.converter.image) ba = QtCore.QByteArray() buff = QtCore.QBuffer(ba) image.save(buff, "PNG") th = threading.Thread(target=send_email, args=(*self._info, ba)) th.start()
def shootScreen(self): img = Screenshot.take_screenshot(constant.CLIPBOARD) if img is not None: self.originalPixmap = None self.originalPixmap = QPixmap(img) self.updateScreenshotLabel() byte_array = QtCore.QByteArray() buffer = QtCore.QBuffer(byte_array) buffer.open(QtCore.QIODevice.WriteOnly) self.originalPixmap.save(buffer, 'PNG') self.encoded_pic = buffer.data().toBase64()
def Greyscale(self): image = self.imageName buffer = QtCore.QBuffer() buffer.open(QtCore.QBuffer.ReadWrite) image.save(buffer, "JPG") pil_im = Image.open(io.BytesIO(buffer.data())) im = pil_im.convert('RGB') matrix = (0.2, 0.5, 0.3, 0.0, 0.2, 0.5, 0.3, 0.0, 0.2, 0.5, 0.3, 0.0) result = im.convert('RGB',matrix) self.scene = QtWidgets.QGraphicsScene() self.scene.addPixmap(self.pil2pixmap(result)) self.graphicsView_2.setScene(self.scene) self.graphicsView_2.fitInView(self.scene.itemsBoundingRect())
def getFeedIconAsTextEncodedByteArray(self): """ Returns the feed icon as a base64-encoded string. This is used when exporting a feed as XML. """ pixmap = self.getFeedIcon() if pixmap is not None: buffer = QtCore.QBuffer() buffer.open(QtCore.QIODevice.ReadWrite) pixmap.save(buffer, "PNG") base64ByteArray = buffer.data().toBase64() testByteArray = bytearray(base64ByteArray) base64ByteArrayStr = testByteArray.decode('utf-8') return str(base64ByteArrayStr) else: return ""
def chooseFile(self): self.file = QFileDialog.getOpenFileName(self, 'Open File') pixmap = QtGui.QPixmap(self.file[0]) self.lbl.setPixmap(pixmap.scaledToHeight(201)) if self.file != None: ba = QtCore.QByteArray() buff = QtCore.QBuffer(ba) buff.open(QtCore.QIODevice.WriteOnly) ok = pixmap.save(buff, "PNG") assert ok pixmap_bytes = ba.data() #print(type(pixmap_bytes)) #data = self.file[0] self.stri = base64.b64encode(pixmap_bytes)
def grabar(self): regMarco = self.liEjemplos[0].bloqueDatos nombre = regMarco.nombre.strip() if nombre == "": QTUtil2.mensError(self, _("Name missing")) return self.regMarco = regMarco pm = self.liEjemplos[0].pixmap() bf = QtCore.QBuffer() pm.save(bf, "PNG") self.regMarco.png = bf.buffer().data() self.accept()
def convertImage(self): byte_array = QtCore.QByteArray() buffer = QtCore.QBuffer(byte_array) buffer.open(QtCore.QIODevice.WriteOnly) if fileName == '': if pixMap.toImage().isNull() is True: return else: pixMap.save(buffer, "jpg") else: pixMap.save(buffer, fileName.split('.')[-1]) ls_f = base64.b64encode(bytes(buffer.data())) self.base64View.setText("[base64str]:data:image/png;base64," + ls_f.decode("utf-8"))
def qImageToPilImage(qimage): """ Convert a QImage to a PIL Image. http://stackoverflow.com/a/1756587/4718769 """ buffer = QtCore.QBuffer() buffer.open(QtCore.QIODevice.ReadWrite) qimage.save(buffer, 'PNG') bio = io.BytesIO() bio.write(buffer.data()) buffer.close() bio.seek(0) return PIL.Image.open(bio)