dyzu
dyzu

Reputation: 33

How to change opacity of rectangle in PIL?

I am trying to achieve something similar to the image below, with the translucent black box with the writing on: Desired

Ignore the fact that they are different images, but I want to achieve a similar translucent rectangle effect like on the image above. The code I currently have is:

from PIL import Image, ImageDraw

img = Image.new('RGBA', (512, 512), (255, 0, 0, 0))
draw = ImageDraw.Draw(img, 'RGBA')
shape = [(0, 512), (512, 308)]
draw.rectangle(shape, fill = 'black')

img.save('foo.png')


img2 = Image.open('final2.png')


Image.alpha_composite(img2, img).save('foo3.png')

This produces the following output:

Output (ignore white border - its just a rough screenshot)

I've tried putalpha but it just makes the black rectangle grey and still opaque. Also, I've tried creating a transparent image with the same size as the image I want the box drawn on (512x512) and then drawing a rectangle at the bottom of that transparent image then using blend, but the colours of the image mess up because of the white image being blended on top.

Any help is appreciated.

EDIT: Still need help!

Upvotes: 3

Views: 3329

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207903

Please be careful to supply input, output and expected output images in future. I made the following text overlay on a transparent background and added a magenta border so you can see its extent:

enter image description here

Then I recast your code as:

#!/usr/bin/env python3

from PIL import Image, ImageDraw

# Create new solid red background
h, w = 400, 600
bg = Image.new('RGB', (w, h), (255, 0, 0))

# Create copy and make bottom part black
dark = bg.copy()
draw  = ImageDraw.Draw(dark)
draw.rectangle((0, int(0.7*h), w, h), 0)
dark.save('dark.png')   # DEBUG

# Blend darkened copy over top of background
blended = Image.blend(bg, dark, 0.8) 
blended.save('blended.png')   # DEBUG

# Load text overlay with transparent background, paste on top and save
overlay = Image.open('text.png').convert('RGBA')
blended.paste(overlay, mask=overlay)
blended.save('result.png')

That gives this result:

enter image description here

Upvotes: 2

Related Questions