使用枕头alpha_composite
仅适用于相同大小的图像,我想将一个集团粘贴到一个特定的位置并保持其alpha通道。
更具体地说,我想多次复制/粘贴一张半透明的图片到另一张,在背景图片上。
你怎么能用枕头做到这一点?
这是我的代码:
el_width, el_height = 100, 300
img = Image.open('partition.png')
img = img.convert("RGBA")
img_rect = Image.new('RGBA', (el_width, el_height), (0, 0, 0, 100))
draw = ImageDraw.Draw(img_rect)
# draw a semi-transparent rectangle:
draw.rectangle((0, 0, el_width, el_height), outline=(50, 155, 50, 155))
del draw
# trying to paste it:
img.paste(img_rect, (10, 10))
img.show()
结果是,您可以看到矩形是透明的,但是使用“粘贴”时会忽略其透明性:
答案 0 :(得分:0)
也许这段代码可以帮助您
from PIL import Image
import glob
foreground_name = 'BFB_Logo.png'
foreground = Image.open(foreground_name)
foreground = foreground.convert('RGBA')
for file_name in glob.glob('*.jpg'):
print(file_name)
background_name = file_name
background = Image.open(background_name)
# set position there
x = int((background.size[0] / 2) - (foreground.size[0] / 2))
y = int((background.size[1] / 2) - (foreground.size[1] / 2))
background = background.convert('RGBA')
background.paste(foreground, (x, y), mask = foreground)
background.save('__{}.jpg'.format(background_name.split('.')[0]),'JPEG')
print('Ready')