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 imsave(filename, img, format_str=None): warn( '`qt` plugin is deprecated and will be removed in 0.20. ' 'For alternatives, refer to ' 'https://scikit-image.org/docs/stable/user_guide/visualization.html', FutureWarning, stacklevel=2) # we can add support for other than 3D uint8 here... img = prepare_for_display(img) qimg = QImage(img.data, img.shape[1], img.shape[0], img.strides[0], QImage.Format_RGB888) if _is_filelike(filename): byte_array = QtCore.QByteArray() qbuffer = QtCore.QBuffer(byte_array) qbuffer.open(QtCore.QIODevice.ReadWrite) saved = qimg.save(qbuffer, format_str.upper()) qbuffer.seek(0) filename.write(qbuffer.readAll().data()) qbuffer.close() else: saved = qimg.save(filename) if not saved: from textwrap import dedent msg = dedent('''The image was not saved. Allowable file formats for the QT imsave plugin are: BMP, JPG, JPEG, PNG, PPM, TIFF, XBM, XPM''') raise RuntimeError(msg)
def insertImage(self): filename = QtWidgets.QFileDialog.getOpenFileName(caption="Select an image", directory=".", filter="Image Files (*.png *.jpg *.bmp)") image = QtGui.QImage(filename) # Error if unloadable if image.isNull(): popup = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Critical, "Image load error", "Could not load image file!", QtWidgets.QMessageBox.Ok, self) popup.show() else: # encode to base64 to embed image directly in html: ba = QtCore.QByteArray() buf = QtCore.QBuffer(ba) buf.open(QtCore.QIODevice.WriteOnly) image.save(buf, 'PNG') encoded = ba.toBase64().data() # insert to html: cursor = self.text.textCursor() # cursor.insertImage(image,filename) cursor.insertHtml( '''<img src="data:image/png;base64,%s", alt="beastie.png"''' % encoded)
def serializejson_QPixmap(self): ba = QtCore.QByteArray() buff = QtCore.QBuffer(ba) buff.open(QtCore.QIODevice.WriteOnly) ok = self.save(buff, "png") assert ok data = ba.data() # fait une copie ? return type_str(self), tuple(), {"data": data}
def default_pixmap_as_bytes(self): xres = self.imgsize pixmap = icons.cola().pixmap(xres) byte_array = QtCore.QByteArray() buf = QtCore.QBuffer(byte_array) buf.open(QtCore.QIODevice.WriteOnly) pixmap.save(buf, 'PNG') buf.close() return byte_array
def serializejson_QBitmap(self): ba = QtCore.QByteArray() buff = QtCore.QBuffer(ba) buff.open(QtCore.QIODevice.WriteOnly) ok = self.save(buff, "PBM") assert ok data = ba.data() # fait une copie ? return f"QtGui.QBitmap.fromData", ( data, ) # rien à partir de la fonction fromData ne permet de savoir qu'elle est une methode de QImage , ni à quel module ell
def imsave(filename, img, format_str=None): # we can add support for other than 3D uint8 here... img = prepare_for_display(img) qimg = QImage(img.data, img.shape[1], img.shape[0], img.strides[0], QImage.Format_RGB888) if _is_filelike(filename): byte_array = QtCore.QByteArray() qbuffer = QtCore.QBuffer(byte_array) qbuffer.open(QtCore.QIODevice.ReadWrite) saved = qimg.save(qbuffer, format_str.upper()) qbuffer.seek(0) filename.write(qbuffer.readAll().data()) qbuffer.close() else: saved = qimg.save(filename) if not saved: from textwrap import dedent msg = dedent('''The image was not saved. Allowable file formats for the QT imsave plugin are: BMP, JPG, JPEG, PNG, PPM, TIFF, XBM, XPM''') raise RuntimeError(msg)
def _get_image_tag(self, match, path=None, format="png"): """ Return (X)HTML mark-up for the image-tag given by match. Parameters ---------- match : re.SRE_Match A match to an HTML image tag as exported by Qt, with match.group("Name") containing the matched image ID. path : string|None, optional [default None] If not None, specifies a path to which supporting files may be written (e.g., for linked images). If None, all images are to be included inline. format : "png"|"svg"|"jpg", optional [default "png"] Format for returned or referenced images. """ if format in ("png", "jpg"): try: image = self._get_image(match.group("name")) except KeyError: return "<b>Couldn't find image %s</b>" % match.group("name") if path is not None: ensure_dir_exists(path) relpath = os.path.basename(path) if image.save( "%s/qt_img%s.%s" % (path, match.group("name"), format), "PNG"): return '<img src="%s/qt_img%s.%s">' % ( relpath, match.group("name"), format) else: return "<b>Couldn't save image!</b>" else: ba = QtCore.QByteArray() buffer_ = QtCore.QBuffer(ba) buffer_.open(QtCore.QIODevice.WriteOnly) image.save(buffer_, format.upper()) buffer_.close() return '<img src="data:image/%s;base64,\n%s\n" />' % ( format, re.sub(r'(.{60})', r'\1\n', str(ba.toBase64().data().decode()))) elif format == "svg": try: svg = str(self._name_to_svg_map[match.group("name")]) except KeyError: if not self._svg_warning_displayed: QtWidgets.QMessageBox.warning( self, 'Error converting PNG to SVG.', 'Cannot convert PNG images to SVG, export with PNG figures instead. ' 'If you want to export matplotlib figures as SVG, add ' 'to your ipython config:\n\n' '\tc.InlineBackend.figure_format = \'svg\'\n\n' 'And regenerate the figures.', QtWidgets.QMessageBox.Ok) self._svg_warning_displayed = True return ( "<b>Cannot convert PNG images to SVG.</b> " "You must export this session with PNG images. " "If you want to export matplotlib figures as SVG, add to your config " "<span>c.InlineBackend.figure_format = 'svg'</span> " "and regenerate the figures.") # Not currently checking path, because it's tricky to find a # cross-browser way to embed external SVG images (e.g., via # object or embed tags). # Chop stand-alone header from matplotlib SVG offset = svg.find("<svg") assert (offset > -1) return svg[offset:] else: return '<b>Unrecognized image format</b>'