Python Wand将PDF转换为PNG禁用透明(alpha_channel)

Mun*_*nro 18 python imagemagick wand

我正在尝试将PDF转换为PNG - 这一切都运行正常,但是,即使我相信我已将其禁用,输出图像仍然是透明的:

with Image(filename='sample.pdf', resolution=300) as img:
    img.background_color = Color("white")
    img.alpha_channel = False
    img.save(filename='image.png')
Run Code Online (Sandbox Code Playgroud)

以上产生图像但透明,我也试过以下:

with Image(filename='sample.pdf', resolution=300, background=Color('white')) as img:
    img.alpha_channel = False
    img.save(filename='image.png')
Run Code Online (Sandbox Code Playgroud)

产生此错误:

Traceback (most recent call last):
  File "file_convert.py", line 20, in <module>
    with Image(filename='sample.pdf', resolution=300, background=Color('white')) as img:
  File "/Users/Frank/.virtualenvs/wand/lib/python2.7/site-packages/wand/image.py", line 1943, in __init__
    raise TypeError("blank image parameters can't be used with image "
TypeError: blank image parameters can't be used with image opening parameters
Run Code Online (Sandbox Code Playgroud)

Man*_*anu 10

我也有一些PDF转换为PNG.这对我有用,看起来比合成图像更简单,如上图所示:

all_pages = Image(blob=self.pdf)        # PDF will have several pages.
single_image = all_pages.sequence[0]    # Just work on first page
with Image(single_image) as i:
    i.format = 'png'
    i.background_color = Color('white') # Set white background.
    i.alpha_channel = 'remove'          # Remove transparency and replace with bg.
Run Code Online (Sandbox Code Playgroud)

参考:wand.image


emc*_*lle 9

从上一个答案,尝试创建一个背景颜色的空图像,然后合成.

from wand.image import Image
from wand.color import Color

with Image(filename="sample.pdf", resolution=300) as img:
  with Image(width=img.width, height=img.height, background=Color("white")) as bg:
    bg.composite(img,0,0)
    bg.save(filename="image.png")
Run Code Online (Sandbox Code Playgroud)


Thi*_*tio 7

编译其他答案,这是我用来将PDF转换为页面的函数:

import os
from wand.image import Image
from wand.color import Color


def convert_pdf(filename, output_path, resolution=150):
    """ Convert a PDF into images.

        All the pages will give a single png file with format:
        {pdf_filename}-{page_number}.png

        The function removes the alpha channel from the image and
        replace it with a white background.
    """
    all_pages = Image(filename=filename, resolution=resolution)
    for i, page in enumerate(all_pages.sequence):
        with Image(page) as img:
            img.format = 'png'
            img.background_color = Color('white')
            img.alpha_channel = 'remove'

            image_filename = os.path.splitext(os.path.basename(filename))[0]
            image_filename = '{}-{}.png'.format(image_filename, i)
            image_filename = os.path.join(output_path, image_filename)

            img.save(filename=image_filename)
Run Code Online (Sandbox Code Playgroud)