Python报错解决:img2pdf.AlphaChannelError: Refusing to work on images with alpha channel

img2pdf.AlphaChannelError: Refusing to work on images with alpha channel-solved
解决img2pdf模块不能上传含alpha通道透明度的图片的问题
解决img2pdf模块PNG图片转PDF文件因alpha通道报错问题

文章目录

  • 前言
  • 一、AlphaChannelError为什么出现?
  • 二、该种报错解决方法
    • 1.方法一:转化其他格式图片
    • 2.方法二:去除png图片的alpha通道属性
  • 参考资料


前言

Python中的img2pdf库是非常好用的一个将图片转化为PDF文件的库,用起来非常方便。但是当我们在使用该库时,难免会出现一些报错。这次介绍如何用简单的方法解决Python报错:img2pdf.AlphaChannelError: Refusing to work on images with alpha channel。这个报错是在将png格式图片转化为PDF文件时出现的。


一、AlphaChannelError为什么出现?

由于在png格式图片含有alpha通道属性(透明度属性),而PDF文件本身是没有这个属性的。所以,在png格式图片转化为PDF文件时,会报错:img2pdf.AlphaChannelError: Refusing to work on images with alpha channel。因此,我们要想法把png格式图片中的alpha通道属性给去掉。

二、该种报错解决方法

1.方法一:转化其他格式图片

可以采用格式工厂等软件将其先转化为其他格式图片(如:jpg,tif,bmp格式等)。也可以通过Python代码将其转化格式,其代码从文末参考资料第二个链接进入。

2.方法二:去除png图片的alpha通道属性

在将png格式图片转化为PDF文件时,原始代码会报错(img2pdf.AlphaChannelError: Refusing to work on images with alpha channel)代码如下:

# img2pdf模块不能上传含alpha通道透明度的图片
import img2pdf

# 图片地址
img_path = 'C:/Users/admin/Desktop/1/aini.png'
# 合成PDF的名称
file_name = '文件名字'
# PDF保存路径
file_name_real = 'C:/Users/admin/Desktop/1' + '/' + file_name + '.pdf'
# 写出PDF
with open(file_name_real, "wb") as f:
    pfn_bytes = img2pdf.convert(img_path)
    f.write(pfn_bytes)
    print("转换完成")
# 在将png格式图片转化为PDF文件时
# 报错:img2pdf.AlphaChannelError: Refusing to work on images with alpha channel

遇到这种报错,可通过python中的PIL库来读取该png格式图片,然后调用convert函数来去掉alpha通道属性,再重新保存该图片,代码如下:

# img2pdf模块不能上传含alpha通道透明度的图片
import img2pdf
from PIL import Image

# 图片地址
img_path = 'C:/Users/admin/Desktop/1/aini.png'
# 合成PDF的名称
file_name = '文件名字'
# PDF保存路径
file_name_real = 'C:/Users/admin/Desktop/1' + '/' + file_name + '.pdf'

# 解决报错img2pdf.AlphaChannelError: Refusing to work on images with alpha channel
# [-4:]提取字符串最后四个字符
if img_path[-4:] == ".png" or img_path[-4:] == ".PNG":
    img = Image.open(img_path)
    # 将PNG中RGBA属性变为RGB,即可删掉alpha透明度通道
    img.convert('RGB').save(img_path)
    
# 写出PDF
with open(file_name_real, "wb") as f:
    pfn_bytes = img2pdf.convert(img_path)
    f.write(pfn_bytes)
    print("转换完成")

通添加四行代码成功解决报错:img2pdf.AlphaChannelError: Refusing to work on images with alpha channel。


参考资料

python img2pdf 模块不能上传含alpha通道透明度的图片:
https://blog.csdn.net/coco_link/article/details/106303924
Python-png转换成jpg:
https://blog.csdn.net/weixin_40446557/article/details/104059660

作者创作不易,如果对你有帮助,可以点赞或者关注作者,支持一下呗!

你可能感兴趣的:(python,人工智能)