def get_icon_html(icon: QIcon, size: QSize) -> str: """ Transform an icon to html <img> tag. """ if not size.isValid(): return "" if size.width() < 0 or size.height() < 0: size = QSize(16, 16) # just in case byte_array = QByteArray() buffer = QBuffer(byte_array) buffer.open(QIODevice.WriteOnly) pixmap = icon.pixmap(size) if pixmap.isNull(): return "" pixmap.save(buffer, "PNG") buffer.close() dpr = pixmap.devicePixelRatioF() if dpr != 1.0: size_ = pixmap.size() / dpr size_part = ' width="{}" height="{}"'.format( int(math.floor(size_.width())), int(math.floor(size_.height())) ) else: size_part = '' img_encoded = byte_array.toBase64().data().decode("utf-8") return '<img src="data:image/png;base64,{}"{}/>'.format(img_encoded, size_part)
def get_html_img(scene): """ Create HTML img element with base64-encoded image from the scene """ byte_array = QByteArray() filename = QBuffer(byte_array) filename.open(QIODevice.WriteOnly) PngFormat.write(filename, scene) img_encoded = byte_array.toBase64().data().decode("utf-8") return "<img src='data:image/png;base64,%s'/>" % img_encoded
def get_html_img(scene: QGraphicsScene, max_height: Optional[int] = None) -> str: """ Create HTML img element with base64-encoded image from the scene. If max_height is not none set the max height of the image in html. """ byte_array = QByteArray() filename = QBuffer(byte_array) filename.open(QIODevice.WriteOnly) PngFormat.write(filename, scene) img_encoded = byte_array.toBase64().data().decode("utf-8") return '<img {} src="data:image/png;base64,{}"/>'.format( ("" if max_height is None else 'style="max-height: {}px"'.format(max_height)), img_encoded)