首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >img2pdf AlphaChannelError:什么是去除alphachannel的最佳方法

img2pdf AlphaChannelError:什么是去除alphachannel的最佳方法
EN

Stack Overflow用户
提问于 2021-06-28 15:56:19
回答 2查看 649关注 0票数 2

我有一组图像,我根据下面的代码创建pdf

代码语言:javascript
复制
with io.BytesIO() as tmp_io:
    tmp_io.write(img2pdf.convert(img_file_paths))
    result_bytes = tmp_io.getvalue()

其中一个文件包含alpha通道

提高AlphaChannelError(“拒绝处理带有alpha通道的图像”)

删除alpha通道并保存到pdf rgb通道的最简单方法是什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-06-28 16:14:46

这是我自己的一些丑陋的解决方案。

代码语言:javascript
复制
def remove_alpha_from_image(image_path):
    im = Image.open(image_path)
    im.load()
    try:
        background = Image.new("RGB", im.size, (255, 255, 255))
        background.paste(im, mask=im.split()[3])  # 3 is the alpha channel
        im = background
    except IndexError:  # img is not RGBA
        pass

    name_hash_md5 = md5(bytes(image_path, encoding="utf-8"))  # noqa: S303
    name = name_hash_md5.hexdigest()
    if not os.path.exists(TMP_DIR):
        os.makedirs(TMP_DIR)
    path = f"{TMP_DIR}{name}.pdf"
    im.save(path, "PNG", resolution=100.0)
    return path

with io.BytesIO() as tmp_io:
    try:
        tmp_io.write(img2pdf.convert(file_paths))
    except img2pdf.AlphaChannelError:
        tmp_io.write(img2pdf.convert([remove_alpha_from_image(path) for path in file_paths]))

    result_bytes = tmp_io.getvalue()
票数 1
EN

Stack Overflow用户

发布于 2022-02-23 21:39:32

这里有一个我放在一起的实用程序--只在一个应用程序中测试,所以不确定它有多普遍,但应该是交钥匙的。在python 3.9中测试

代码语言:javascript
复制
def image2pdf(image: bytes or str, allow_lossy=True, **rgba_to_kwds) -> bytes:
    """
    Converts an image to PDF, optionally allowing for lossy conversion.
    :param image: if non RGBA image, this can be any valid input to img2pdf.  If RGBA, then must be str (ie. path to image)
                  or bytes representation of image.
    :param allow_lossy: if img2pdf.convert fails with AlphaChannelError, tries to downsample
    :param rgba_to_kwds: kwds to _rgba_to
    :return: bytes representation of PDF image.  To save to disk
           pdfBytes=image2pdf(someImage)
           with open('converted.pdf', 'w') as f:
                f.write(pdfBytes)
    """
    try:
        pdf_bytes = img2pdf.convert(image)
    except img2pdf.AlphaChannelError as alphaError:
        if allow_lossy:
            rgbBytes = _rgba_to(image)
            pdf_bytes = img2pdf.convert(rgbBytes, **rgba_to_kwds)
        else:
            raise alphaError
    return pdf_bytes


def _rgba_to(image: bytes or str, to='RGB', intermediate='PNG') -> bytes:
    logging.warning(f"Image has alpha channel... downsampling (newtype={to}, intermediate={intermediate}) and converting")

    # Image is a filepath
    if isinstance(image, str):
        img = Image.open(image)
        converted: Image = img.convert(to)

    # Image is a bytestream
    elif isinstance(image, bytes):
        buffered = io.BytesIO(image)
        img = Image.open(buffered)
        converted: Image = img.convert(to)
    else:
        raise Exception(f"rgba downsampling only supported for images of type str (ie. filepath) or bytes - got {type(image)}")
    buf = io.BytesIO()
    converted.save(buf, format=intermediate)
    byte_im = buf.getvalue()
    return byte_im

def test_convert_png_image_with_alphachannel_to_pdf():img_path =“some Image.png”pdf_bytes = image2pdf(img_path)

代码语言:javascript
复制
# Uncomment if want to view the pdf
with open('converted.pdf', "wb") as f:
    f.write(pdf_bytes)
代码语言:javascript
复制
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68166470

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档