[英]How can I print preview an image with PyQt5?
I'm trying to print preview a PIL image using QPrintPreviewDialog()
how can I do that?我正在尝试使用
QPrintPreviewDialog()
打印预览 PIL 图像,我该怎么做?
To convert a PIL image to a pixmap (so you can print it) you can use this function:要将 PIL 图像转换为像素图(以便打印),您可以使用此 function:
def pil2pixmap(im):
if im.mode == "RGB":
r, g, b = im.split()
im = IM.merge("RGB", (b, g, r))
elif im.mode == "RGBA":
r, g, b, a = im.split()
im = IM.merge("RGBA", (b, g, r, a))
elif im.mode == "L":
im = im.convert("RGBA")
im2 = im.convert("RGBA")
data = im2.tobytes("raw", "RGBA")
qim = QtGui.QImage(data, im.size[0], im.size[1], QtGui.QImage.Format_ARGB32)
qim = qim.smoothScaled(int(2480 / 3.2), int(3508 / 3.2))
pixmap = QtGui.QPixmap.fromImage(qim)
return pixmap
Source for the code above: https://stackoverflow.com/a/48705903/16592435上述代码的来源: https://stackoverflow.com/a/48705903/16592435
And then to preview an image you can use this function:然后预览图像,您可以使用此 function:
def print_image(image):
# Initializes the QPainter and draws the pixmap onto it
def drawImage(printer):
painter = QPainter()
painter.begin(printer)
painter.setPen(Qt.red)
painter.drawPixmap(0, 0, pil2pixmap(image))
painter.end()
# Shows the preview
app = QApplication(sys.argv)
dlg = QPrintPreviewDialog()
dlg.paintRequested.connect(drawImage)
dlg.exec_()
app.exec_()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.