【问题标题】:How do i set the max size for an image in Reportlab, without rescaling?如何在不重新缩放的情况下在 Reportlab 中设置图像的最大尺寸?
【发布时间】:2013-06-18 09:47:42
【问题描述】:

我正在尝试使用 Reportlab 生成 pdf。这是可以接受的容易。我有一个类似下面的函数,它返回图像,我只是将它添加到文档中。

def create_logo(bsolute_path):
   image = Image(absolute_path)
   image.drawHeight = 1 * inch
   image.drawWidth = 2 * inch
   return [image]

它有效,但不是我想要的。我遇到的问题是它重新调整了我的图像。 例如。如果我有一个比例为 1 到 3 的 3000 像素(宽度)x 1000 像素(高度)的图像,我会在 pdf 中得到一个重新缩放的图像:1 到 2。

如果图像太大,我基本上想要的是指定最大宽度和高度并让reportlab调整它的大小(而不是重新调整它)。

这可以在 Reportlab 中完成还是我应该自己完成?

谢谢!

【问题讨论】:

    标签: python image pdf reportlab


    【解决方案1】:

    您可以设置preserveAspectRatio=True。所以比例应该是预期的 1:3。

    drawImage(image, x, y, width=None, height=None, mask=None, preserveAspectRatio=True, anchor='c')
    

    您可以将比例因子添加为常数。

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      我也发现了这个:

      Image aspect ratio using Reportlab in Python

      但最后我还是用了这个方法:

      def create_logo(absolute_path):
          image = Image(absolute_path)
          image._restrictSize(2 * inch, 1 * inch)
      

      【讨论】:

        【解决方案3】:

        这对我有用:

        image = Image(absolute_path,width=2*inch,height=1*inch,kind='proportional')
        

        【讨论】:

          【解决方案4】:

          虽然我的回答对你来说为时已晚,但对于其他有同样问题的人来说。您的图像缩放问题可以通过了解图像的 dpi 来解决。 我有一张 59x19 像素的图像,我想粘贴到 pdf 上。我是如何成功的如下。

          from reportlab .pdfgen import canvas
          from reportlab.lib.utils import ImageReader
          from reportlab.lib.pagesizes import A4
          from reportlab.lib.units import mm
          xloc=10
          yloc=10
          c=canvas.Canvas(pdfPath,pagesize=A4) # put you pdf path here
          c.draw(image, xloc,yloc,15*mm,5*mm)
          

          现在 96dpi 的 59px 以 mm 为单位转换为 15mm,类似地 96dpi 的 19px 将是 5mm。 见https://www.pixelto.net/px-to-mm-converter。这将保留您的纵横比。我也观察到一些奇怪的东西。 59px 实际上是 15.610416667mm 但如果我也使用小数部分,图像会模糊。

          【讨论】:

            猜你喜欢
            • 2019-12-13
            • 2022-11-18
            • 1970-01-01
            • 1970-01-01
            • 2016-01-09
            • 2011-10-14
            • 1970-01-01
            • 1970-01-01
            • 2021-12-13
            相关资源
            最近更新 更多