JavaScript
x
13
13
1
from PIL import Image
2
from PIL import ImageDraw
3
from io import BytesIO
4
from urllib.request import urlopen
5
6
url = "https://i.ytimg.com/vi/W4qijIdAPZA/maxresdefault.jpg"
7
file = BytesIO(urlopen(url).read())
8
img = Image.open(file)
9
img = img.convert("RGBA")
10
draw = ImageDraw.Draw(img, "RGBA")
11
draw.rectangle(((0, 00), (img.size[0], img.size[1])), fill=(0,0,0,127))
12
img.save('dark-cat.jpg')
13
This is giving me a giant black square. I want it to be a semi transparent black square with a cat. Any Ideas?
Advertisement
Answer
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.
JavaScript
1
39
39
1
from PIL import Image, ImageDraw
2
from io import BytesIO
3
from urllib.request import urlopen
4
5
TINT_COLOR = (0, 0, 0) # Black
6
TRANSPARENCY = .25 # Degree of transparency, 0-100%
7
OPACITY = int(255 * TRANSPARENCY)
8
9
url = "https://i.ytimg.com/vi/W4qijIdAPZA/maxresdefault.jpg"
10
with BytesIO(urlopen(url).read()) as file:
11
img = Image.open(file)
12
img = img.convert("RGBA")
13
14
# Determine extent of the largest possible square centered on the image.
15
# and the image's shorter dimension.
16
if img.size[0] > img.size[1]:
17
shorter = img.size[1]
18
llx, lly = (img.size[0]-img.size[1]) // 2 , 0
19
else:
20
shorter = img.size[0]
21
llx, lly = 0, (img.size[1]-img.size[0]) // 2
22
23
# Calculate upper point + 1 because second point needs to be just outside the
24
# drawn rectangle when drawing rectangles.
25
urx, ury = llx+shorter+1, lly+shorter+1
26
27
# Make a blank image the same size as the image for the rectangle, initialized
28
# to a fully transparent (0% opaque) version of the tint color, then draw a
29
# semi-transparent version of the square on it.
30
overlay = Image.new('RGBA', img.size, TINT_COLOR+(0,))
31
draw = ImageDraw.Draw(overlay) # Create a context for drawing things on it.
32
draw.rectangle(((llx, lly), (urx, ury)), fill=TINT_COLOR+(OPACITY,))
33
34
# Alpha composite these two images together to obtain the desired result.
35
img = Image.alpha_composite(img, overlay)
36
img = img.convert("RGB") # Remove alpha for saving in jpg format.
37
img.save('dark-cat.jpg')
38
img.show()
39
Here’s the result of applying it to your test image: