问题描述
with io.BytesIO() as tmp_io:
tmp_io.write(img2pdf.convert(img_file_paths))
result_bytes = tmp_io.getvalue()
raise AlphaChannelError("拒绝处理带有 alpha 通道的图像")
删除 alpha 通道并保存到 pdf rgb 通道的最简单方法是什么?
解决方法
这是我自己的有点丑陋的解决方案
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()