【问题标题】:Python Magickwand pdf to image converting and resize the imagePython Magickwand pdf到图像转换和调整图像大小
【发布时间】:2012-09-27 09:47:56
【问题描述】:

我需要创建 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")

【问题讨论】:

    标签: imagemagick python-2.6 magickwand


    【解决方案1】:

    我找到了解决这个问题的方法。 将 pdf 转换为图像 1st 并保存图像。打开新保存的图像并调整其大小。

    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")
    

    我还在等待更好的答案。

    【讨论】:

    • 我建议中间保存到 "d:\\temp.jpg" 使用无损格式,以免在最终图像中引入任何额外的压缩伪影。
    【解决方案2】:

    如果您不依赖 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")
    

    【讨论】:

      【解决方案3】:

      我今天遇到了同样的问题。我在其他帖子中找到了另一个解决方案。 图像变黑的原因是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 convert PDF to PNG disable transparent (alpha_channel)

      【讨论】:

        猜你喜欢
        • 2018-12-19
        • 2018-02-01
        • 2017-08-22
        • 1970-01-01
        • 2011-03-30
        • 2016-08-25
        • 1970-01-01
        • 1970-01-01
        • 2012-09-07
        相关资源
        最近更新 更多