簡體   English   中英

Python Wand從PDF轉換為JPG背景不正確

[英]Python Wand converts from PDF to JPG background is incorrect

我在將pdf轉換為jpeg時找到了一個如此有線的東西,所以我想弄清楚這可能是一個小bug。 看下面轉換的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

你可以試試...

一個簡單的解決方案是更改命令的順序:首先將格式更改為jpeg,然后再調整大小

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

通過分辨率元組打開精確大小的PDF也很容易,因為分辨率可以是浮點數。

對於仍然有這個問題的其他人,我通過谷歌搜索並嘗試了幾個小時,由於這個問題https://stackoverflow.com/a/40494320/2686243使用這兩行:

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

嘗試使用Wand版本0.4.4

我自己得到了答案。 這是因為alpha_channel案例。 這個pdf包括一些透明背景(在我轉換為png格式之后),並且對於調整大小,ImageMagick選擇最佳調整大小的濾鏡,因此顯示黑色背景。

因此,經過大量實驗,我發現只需在“with”語句中添加“img.alpha_channel = False”(在img.save()之前),這將正常工作。

感謝VadimR的建議,這很有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM