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

这给了我一个巨大的黑色正方形.我希望它是一个半透明的黑色正方形,上面有一只cat .有什么 idea 吗?

推荐答案

抱歉,我关于它是一个bug的 comments 是不正确的,所以...

您可以通过创建一个临时图像并使用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()

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

picture of a cat with blacken square rectangle superimposed on it

Python-3.x相关问答推荐

类型注释:pathlib. Path vs importlib. resources. abc. Traversable

如何从Django连接到Neo4J s AuraDB(免费层)?'

在Pandas 数据帧中为小于5位的邮政编码添加前导零

将列表项的极列水平分解为新列

逐行比较2个Pandas数据帧,并对每一行执行计算

selenium 无法执行网站上最简单的功能

如何获取实例化 `types.GenericAlias` 的下标类?

如何将搜索结果中的所有值保存在另一个列表中?

txt 文件与不同的分隔符到整数列表

以不规则频率识别数据框日期时间列上缺失的日期,并用关联值填充它们

将 pandas Timestamp() 转换为 datetime.datetime() 以支持 peewee DateTimeField()

如何通过从特定列创建分组多标题来reshape 数据框?

ValueError:FixedLocator 位置的数量 (5),通常来自对 set_ticks 的调用,与刻度标签的数量 (12) 不匹配

使用 Python 3 按行进行分析

如何在 FastAPI 中的一条路由上捕获任意路径?

计数大于Pandas groupby 中的值的项目

Python 3 中的连接列表

当默认 pip 为 pip2 时,升级 pip3 的正确格式是什么?

Django Rest 框架 ListField 和 DictField

TypeError:无法实例化类型元组;使用 tuple() 代替