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 image_data(pm): # type: (QPixmap) -> str """ Render the contents of the pixmap as a data URL (RFC-2397) Parameters ---------- pm : QPixmap Returns ------- datauri : str """ pm = QPixmap(pm) device = QBuffer() assert device.open(QBuffer.ReadWrite) pm.save(device, b"png") device.close() data = bytes(device.data()) payload = base64.b64encode(data).decode("ascii") return "data:image/png;base64," + payload
def image_data(pm): # type: (QPixmap) -> str """ Render the contents of the pixmap as a data URL (RFC-2397) Parameters ---------- pm : QPixmap Returns ------- datauri : str """ pm = QPixmap(pm) device = QBuffer() assert device.open(QBuffer.ReadWrite) pm.save(device, b'png') device.close() data = bytes(device.data()) payload = base64.b64encode(data).decode("ascii") return "data:image/png;base64," + payload