Python Magickwand PDF 转图像并调整图像大小

9
我需要创建pdf文件缩略图,我正在使用Imagemagick来实现。我尝试了Pythonmagick和wand将pdf转换为图像。但是,当我试图调整转换后的pdf大小时,结果的图像会变成黑色。是否有选项可以使用Python包装器来设置-define pdf:use-cropbox=true? 是否有其他方法在Python中将pdf转换为缩略图?以下是代码:
    import wand
    img = wand.image.Image(filename="d:\\test.pdf[0]")
    img.resize(160,160)
    img.save(filename="d:\\test.jpg")
3个回答

5
我找到了解决这个问题的方法。 首先将pdf转换为图像并保存该图像。然后打开新保存的图像并调整大小。
import wand
img = wand.image.Image(filename="d:\\test.pdf[0]")
img.save(filename="d:\\temp.jpg")
img = wand.image.Image(filename="d:\\temp.jpg")
img.resize(160,160)
img.save(filename="d:\\resized_image.jpg")

我仍在等待更好的答案。


1
我建议将中间保存为“d:\temp.jpg”的格式使用无损压缩,以免在最终图像中引入任何额外的压缩畸变。 - awatts

2
我今天遇到了同样的问题。在其他帖子中,我找到了另一种解决方案。 图片变黑的原因是PDF文件中的背景是透明的。由于JPG文件无法识别alpha通道(记录透明像素信息),JPG文件会将这些透明像素默认设置为黑色。
# Use the following two lines to fix this error
# img_page.background_color = Color('white')
# img_page.alpha_channel = 'remove'

with Image(filename="file.pdf",resolution= 350) as img_pdf:
    num_pages = len(img_pdf.sequence)
    for page, img in enumerate(img_pdf.sequence):
        img_page = Image(image=img)
        img_page.background_color = Color('white')
        img_page.alpha_channel = 'remove'
        img_page.resize(900,1200)
        img_page.save(filename="file"+str(page)+".jpg")
        if page == 0:
            img_page.resize(500, 500)
            img_page.save(filename="thumbnail.jpg")

参考链接: Python Wand将PDF转换为PNG时禁用透明度(alpha_channel)


调用 resize 很可能会扭曲图像的尺寸。如果它们将在网页上显示,最好限制高度或宽度(但不是两者都限制)。 - Tom Russell

0

如果您不依赖于JPG,您可以在不使用临时文件的情况下完成它。

以下方法适用于我:

import wand
img=wand.image.Image(filename="/home/vagrant/tmp/wand/law.pdf[0]")
img.format='png'
img.resize(220,220)
img.save(filename="/home/vagrant/tmp/wand/law_2.png")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接