This commit is contained in:
@ -44,10 +44,34 @@ class NoticeUI:
|
||||
|
||||
image = Image.open(BytesIO(image_bytes)).convert("RGBA")
|
||||
mask = Image.open(BytesIO(mask_bytes)).convert("L")
|
||||
# 应用遮罩
|
||||
image.putalpha(mask)
|
||||
|
||||
# 使用mask作为alpha通道
|
||||
r, g, b, _ = image.split()
|
||||
transparent_image = Image.merge("RGBA", (r, g, b, mask))
|
||||
|
||||
# 先创建一个纯白色背景,然后粘贴透明图像
|
||||
background = Image.new("RGBA", transparent_image.size, (255, 255, 255, 255))
|
||||
composite = Image.alpha_composite(background, transparent_image)
|
||||
|
||||
palette_img = composite.convert("RGB").convert(
|
||||
"P",
|
||||
palette=Image.Palette.WEB,
|
||||
colors=256,
|
||||
dither=Image.Dither.NONE
|
||||
)
|
||||
|
||||
# 将alpha值小于128的设为透明
|
||||
alpha_mask = mask.point(lambda x: 0 if x < 128 else 255)
|
||||
|
||||
# 保存为GIF
|
||||
output_buffer = BytesIO()
|
||||
image.save(output_buffer, format="GIF", disposal=2, loop=0)
|
||||
palette_img.save(
|
||||
output_buffer,
|
||||
format="GIF",
|
||||
transparency=0, # 将索引0设为透明
|
||||
disposal=2,
|
||||
loop=0
|
||||
)
|
||||
|
||||
output_buffer.seek(0)
|
||||
return output_buffer.getvalue()
|
||||
Reference in New Issue
Block a user