首页 > 解决方案 > PIL.Image.alpha_composite - 选择起点

问题描述

我需要将具有 0 alpha 层的图像“粘贴”到另一个图像。为此,我使用 PIL.Image.alpha_composite 函数。它的文档说,这两个图像应该是相同的大小。但这绝对不是真的。此代码显示,我可以混合 2 个不同大小的图像:

from PIL import Image, ImageDraw

image_size = (700, 500)
rect_size = (700, 200)
shape = [(0, 0), rect_size] 

#Create blank image 700x500
im1 = Image.new("RGBA", image_size)

#Create blank image for rectangle drawing 700x200
im2 = Image.new("RGBA", rect_size)

#Draw rectangle on it with the same 700x200 dims
im3 = ImageDraw.Draw(im2) 
im3.rectangle(shape, fill ="#ffff33")

#Composite 2 images of 700x500 and 700x200 sizes
im1.alpha_composite(im2)

im1.show()

结果可能是这样的: 在此处输入图像描述

我的问题是我想把矩形放在底部。有可能以某种方式做吗?

标签: pythonpython-imaging-library

解决方案


Why don't you set im2 size to the image size (700, 500) and draw the rectangle at the bottom of im2. Like this:

from PIL import Image, ImageDraw

image_size = (700, 500)
rect_size = (700, 500)
# Draw rectangle from first point (x=0,y=300) to the second point (x =700,y=500)
shape = (0,300,700,500)

#Create blank image 700x500
im1 = Image.new("RGBA", image_size)

#Create blank image for rectangle drawing 700x200
im2 = Image.new("RGBA", rect_size)


#Draw rectangle on it with the same 700x200 dims
im3 = ImageDraw.Draw(im2)
im3.rectangle(shape, fill ="#ffff33")


#Composite 2 images of 700x500 and 700x200 sizes
im1.alpha_composite(im2)

im1.show()

推荐阅读