3

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!

dyzu
  • 33
  • 1
  • 5
  • I don't see it in [the documentation](https://pillow.readthedocs.io/en/3.0.x/reference/ImageColor.html) but apparently you *can* supply exact RGBA values for the fill [as a tuple](https://stackoverflow.com/a/21768191/2564301). – Jongware Apr 21 '20 at 12:50
  • Does the exact same thing. – dyzu Apr 21 '20 at 21:22
  • Exact same thing with grey box instead of black** – dyzu Apr 21 '20 at 21:41

1 Answers1

1

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

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432