如何解决Python PILPillow-如何在附加到PDF文件的图像上获得不透明度?
目标:将图像保存到文件中(每个图像都有自己的页面)。每个图像上都会添加文字,并且可以打印。
我有一个要与RGBA文本图像(从API提取的文本字符串)组合的图像数组(png),创建一个alpha复合图像(将它们组合),然后附加到PDF文件。问题是,如果我想将其附加到pdf上,则图像不能是RGBA,将其设置为RGB会使背景变为黑色,而不是白色/不透明。
这是代码:
from PIL import Image,ImageDraw,ImageFont
import time
def write_custom_strings(model,strings,font_color):
base = Image.open(f"./label_templates/{model}.png")
# make a blank image for the text,initialized to transparent text color
txt = Image.new('RGBA',base.size,(255,255,1))
image_width = base.size[0]
image_height = base.size[1]
# get a drawing context
d = ImageDraw.Draw(txt)
# Get font
fnt = ImageFont.truetype('./cond_mono.ttf',65)
text_width,text_height = d.textsize(strings)
# draw text
d.multiline_text(((image_width - text_width * 3.5)/2,725),font=fnt,fill=font_color)
out = Image.alpha_composite(base,txt)
out = out.convert('RGB')
out.show() # Show Image in development
return out
def save_to_file(images):
filename = generate_filename()
if len(images) > 0:
images[0].save(f"./product_labels/{filename}",save_all=True,append_images=images[1:])
else:
print("No new items")
def generate_filename():
date = time.localtime()
# Create filename using date/time
return f"Custom-Orders:{str(date.tm_mon)}.{str(date.tm_mday)}.{str(date.tm_year)}-{str(date.tm_hour)}:{str(date.tm_min)}:{str(date.tm_sec)}.pdf"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。