【问题标题】:ReportLab displays images with wrong orientationReportLab 显示方向错误的图像
【发布时间】:2015-12-23 15:57:07
【问题描述】:

我正在使用 reportlab 从 python API 生成 PDF 文档。 这些文件包括图片(之前用相机或移动设备拍摄的),其中加载了:

from reportlab.platypus import Image
img = Image(path)
story.append(img)

问题:某些图像的显示方向不正确(某些 EXIF 数据可能在某些时候丢失或被忽略)。

我曾经在 PIL 上遇到过类似的问题,我选择的解决方案是使用 Wand 而不是 PIL 或 Pillow,但似乎 ReportLab 仅使用 PIL 来处理带有 Python 的图像...

我找到了 this code snippet from another question,但我不确定如何编辑 reportlab 以包含它,或者这是否是一个好方法。

我很惊讶我没有找到关于这个主题的任何内容,我不可能是唯一一个想要在报告实验室生成的 PDF 中包含图片的人...

这是一张图片,左侧是在预览中打开的原始图像,右侧是 PDF:

感谢您的帮助,我已经为此苦苦挣扎了好几个小时...

【问题讨论】:

  • 你能提供一张真实的图片来说明这种行为吗?
  • @MichielOvertoom 我编辑了我的帖子以添加图片。
  • 这是图片在预览中的截图。我对实际图片本身很好奇,所以我可以检查它的内容。

标签: python python-imaging-library reportlab


【解决方案1】:

其实我在使用 pyCairo 时也遇到了同样的问题。

我有一堆JPEG图片,有的直接放到PDF文档中,有的在插入PDF之前用pyCairo处理过。

将 JPEG 图像插入到 reportlab PDF 文档中,或将图像从 JPEG 转换为 PNG 以使用 pyCairo(据我所知,pyCairo 不适用于 JPEG)时,存储在EXIF 会丢失。

这是我最终做的:

from reportlab.platypus import Image
from wand.image import Image as WandImage

def AddAPictureToDocument():

     with WandImage(filename=path) as wimg:
          WandConvertToPNG(wimg,pngDestinationPath)

     img = Image(pngDestinationPath)
     story.append(img)

def WandConvertToPNG(img, savepath):

    exif = {}
    exif.update((k[5:], v) for k, v in img.metadata.items()
                if k.startswith('exif:'))

    orientation = exif['Orientation']

    with img.convert('png') as converted:
        if   int(orientation) == 3 :
            converted.rotate(180)
        elif int(orientation) == 6 :
            converted.rotate(90)
        elif int(orientation) == 8 :
            converted.rotate(270)

    converted.save(filename=savepath)

但它可能会很慢,尤其是使用 pyCairo,因为我需要:

1) 从 JPEG 转换为 PNG,

2) 将图像旋转到正确的方向

3) 使用pyCairo在图像上画东西

4) 将 pyCairo 处理后的图像保存为 PNG

5) 将 PNG 转换为 JPEG 以压缩图像

假设 PIL 或 Wand 等图像库会在 JPEG->PNG 转换后处理图像的方向,是不是太天真了?

无论如何,我仍在寻找更好的解决方案。

【讨论】:

    猜你喜欢
    • 2019-11-27
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 2011-05-27
    • 2015-07-28
    • 1970-01-01
    相关资源
    最近更新 更多