Python魔杖转换PDF到JPG,背景是在

2024-03-29 07:01:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我在将pdf转换为jpeg时发现了一个非常复杂的问题,所以我想弄清楚这可能是一个小错误。 看到下面转换的jpg,你会发现,背景色都是黑色的。 图片如下:www.shdowin.com/public/02.jpg

但是,在pdf的源文件中,可以看到背景颜色是正常的白色。 图片如下:www.shdowin.com/public/normal.jpg

我认为这可能是我的pdf文件的错误,然而,当我尝试在.NET环境中使用Acrobat.pdf2image时,转换后的jpg显示正确。

这是我的代码:

from wand.image import Image
from wand.color import Color
import os, os.path, sys

def pdf2jpg(source_file, target_file, dest_width, dest_height):
    RESOLUTION    = 300
    ret = True
    try:
        with Image(filename=source_file, resolution=(RESOLUTION,RESOLUTION)) as img:
            img.background_color = Color('white')
            img_width = img.width
            ratio     = dest_width / img_width
            img.resize(dest_width, int(ratio * img.height))
            img.format = 'jpeg'
            img.save(filename = target_file)
    except Exception as e:
        ret = False

    return ret

if __name__ == "__main__":
    source_file = "./02.pdf"
    target_file = "./02.jpg"

    ret = pdf2jpg(source_file, target_file, 1895, 1080)

对这个问题有什么建议吗?

我已将pdf上载到url: 02.pdf

你可以试试。。。


Tags: importsourcetargetimgpdfwww错误图片
3条回答

对于其他仍然有这个问题的人,我在谷歌上搜索并尝试了几个小时后通过以下两行代码修复了这个问题https://stackoverflow.com/a/40494320/2686243

img.background_color = Color("white")
img.alpha_channel = 'remove'

尝试使用魔杖版本0.4.4

我自己得到了答案。这是因为阿尔法通道的情况。这个pdf包含一些透明的背景(在我转换成png格式之后),对于resize,ImageMagick选择了最佳的resize过滤器,所以显示黑色背景。

所以,经过大量实验,我发现只要在“with”语句中添加“img.alpha_channel=False”(在img.save()之前),就可以正常工作了。

谢谢瓦迪姆的建议,这很有帮助。

一个简单的解决方案是更改命令的顺序:首先将格式更改为jpeg,然后调整大小

        img.format = 'jpeg'
        img.resize(dest_width, int(ratio * img.height))

也很容易通过解析元组以精确的大小打开PDF,因为解析可以是浮点数。

相关问题 更多 >