Python Wand 从 PDF 转换为 JPG 背景不正确

cen*_*ndy 5 python pdf jpeg image wand

我在将 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)
Run Code Online (Sandbox Code Playgroud)

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

我已将pdf上传到网址: 02.pdf

你可以试试...

cen*_*ndy 2

我自己得到了答案。这是因为 alpha_channel 的情况。该pdf包含一些透明背景(在我转换为png格式之后),并且对于调整大小,ImageMagick选择最佳的调整大小过滤器,因此显示黑色背景。

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

感谢 VadimR 的建议,很有帮助。