【问题标题】:How can I print preview an image with PyQt5?如何使用 PyQt5 打印预览图像?
【发布时间】:2022-01-04 00:41:56
【问题描述】:

我正在尝试使用QPrintPreviewDialog() 打印预览 PIL 图像 我该怎么做?

【问题讨论】:

    标签: python-3.x image-processing printing pyqt5 print-preview


    【解决方案1】:

    要将 PIL 图像转换为像素图(以便打印),您可以使用此函数:

    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
    

    以上代码来源:https://stackoverflow.com/a/48705903/16592435

    然后要预览图像,您可以使用此功能:

    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_()
    

    【讨论】:

      猜你喜欢
      • 2020-04-13
      • 2010-10-09
      • 2015-12-06
      • 1970-01-01
      • 2021-01-05
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多