PIL 在图像上绘制半透明方形叠加层

新手上路,请多包涵
from PIL import Image
from PIL import ImageDraw
from io import BytesIO
from urllib.request import urlopen

url = "https://i.ytimg.com/vi/W4qijIdAPZA/maxresdefault.jpg"
file = BytesIO(urlopen(url).read())
img = Image.open(file)
img = img.convert("RGBA")
draw = ImageDraw.Draw(img, "RGBA")
draw.rectangle(((0, 00), (img.size[0], img.size[1])), fill=(0,0,0,127))
img.save('dark-cat.jpg')

这给了我一个巨大的黑色方块。我希望它是一个带猫的半透明黑色方块。有任何想法吗?

原文由 Chase Roberts 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.1k
2 个回答

抱歉,我关于它是错误的评论是不正确的,所以……

您可以通过创建临时图像并使用 Image.alpha_composite() 来实现,如下面的代码所示。请注意,它支持黑色以外的半透明方块。

 from PIL import Image, ImageDraw
from io import BytesIO
from urllib.request import urlopen

TINT_COLOR = (0, 0, 0)  # Black
TRANSPARENCY = .25  # Degree of transparency, 0-100%
OPACITY = int(255 * TRANSPARENCY)

url = "https://i.ytimg.com/vi/W4qijIdAPZA/maxresdefault.jpg"
with BytesIO(urlopen(url).read()) as file:
    img = Image.open(file)
    img = img.convert("RGBA")

# Determine extent of the largest possible square centered on the image.
# and the image's shorter dimension.
if img.size[0] > img.size[1]:
    shorter = img.size[1]
    llx, lly = (img.size[0]-img.size[1]) // 2 , 0
else:
    shorter = img.size[0]
    llx, lly = 0, (img.size[1]-img.size[0]) // 2

# Calculate upper point + 1 because second point needs to be just outside the
# drawn rectangle when drawing rectangles.
urx, ury = llx+shorter+1, lly+shorter+1

# Make a blank image the same size as the image for the rectangle, initialized
# to a fully transparent (0% opaque) version of the tint color, then draw a
# semi-transparent version of the square on it.
overlay = Image.new('RGBA', img.size, TINT_COLOR+(0,))
draw = ImageDraw.Draw(overlay)  # Create a context for drawing things on it.
draw.rectangle(((llx, lly), (urx, ury)), fill=TINT_COLOR+(OPACITY,))

# Alpha composite these two images together to obtain the desired result.
img = Image.alpha_composite(img, overlay)
img = img.convert("RGB") # Remove alpha for saving in jpg format.
img.save('dark-cat.jpg')
img.show()

这是将其应用于测试图像的结果:

上面叠加有黑色方形矩形的猫的图片

原文由 martineau 发布,翻译遵循 CC BY-SA 4.0 许可协议

鉴于每当我想用 PIL 绘制透明矩形时,我都会不断回到这个问题,所以我决定进行更新。

如果我只更改一件事,您的代码对我来说非常有用:以 PNG 格式而不是 JPEG 格式保存图像。

所以当我跑步时

from io import BytesIO
from urllib.request import urlopen
from PIL import Image
from PIL import ImageDraw

url = "https://i.ytimg.com/vi/W4qijIdAPZA/maxresdefault.jpg"
file = BytesIO(urlopen(url).read())
img = Image.open(file)
draw = ImageDraw.Draw(img, "RGBA")
draw.rectangle(((280, 10), (1010, 706)), fill=(200, 100, 0, 127))
draw.rectangle(((280, 10), (1010, 706)), outline=(0, 0, 0, 127), width=3)
img.save('orange-cat.png')

我得到这个美妙的图像:

带有半透明橙色边界框的猫

原文由 Alexander Pacha 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题