PIL在图像上绘制半透明的正方形叠加层 [英] PIL Drawing a semi-transparent square overlay on image

查看:120
本文介绍了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')

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

This is giving me a giant black square. I want it to be a semi transparent black square with a cat. Any Ideas?

推荐答案

对不起,我对它是一个错误的评论不正确,所以...

Sorry, the comment I made about it being a bug was incorrect, so...

您可以通过创建临时图像并使用

You can do it by creating a temporary image and using Image.alpha_composite() as shown in the code below. Note that it supports semi-transparent squares other than black.

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()

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

Here's the result of applying it to your test image:

这篇关于PIL在图像上绘制半透明的正方形叠加层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆