1
votes

I'm trying to create an image and fill it with a semi-transparent black colour:

  from PIL import Image
  from PIL import ImageFont
  from PIL import ImageDraw
  from PIL import ImageEnhance


  fnt = create_font()

  # my background rectangle
  img1 = Image.new("RGBA", 100, 100, color=(0, 0, 0, 230)) #RGBA
  dr1 = ImageDraw.Draw(img1)
  dr1.text((5, 5), "some text", font=fnt)

  # my source image
  my_img.paste(dr1, (10, 10))
  my_img.save(out_file, "JPEG")

But it ignores the "230" being the transparency level. If I change it to "0" or any other number, the transparency level of "dr1" rectangle stays the same -- it's completely black.

update:

I have a source in jpeg my_img. I want to put a semi-transparent rectangle on its part img1 with a text. How can I do that? How can I get img1 more transparent?

2

2 Answers

4
votes

Firstly, JPEG doesn't support transparency, so if you want an image file with transparency you'll need to use a different format, eg PNG.

I don't know where that create_font function is defined; there isn't a function of that name in my PIL ImageFont (I'm using PIL.PILLOW_VERSION == '3.3.0' on Python 3.6 on 32 bit Linux).

Also, that paste operation won't work, but you don't need it.

Here's a modified version of your code.

from PIL import Image, ImageFont, ImageDraw

img1 = Image.new("RGBA", (100, 100), color=(0, 0, 0, 64))
dr1 = ImageDraw.Draw(img1)
fnt = ImageFont.load_default()
dr1.text((5, 5), "some text", font=fnt, fill=(255, 255, 0, 128))

#img1.show()
img1.save('test.png')

And here's the PNG file it creates:

transparent yellow text on a transparent black background


Here's some code for your updated question.

from PIL import Image, ImageFont, ImageDraw

img1 = Image.open('hueblock.jpg').convert("RGBA")

overlay = Image.new("RGBA", (100, 100), color=(0, 0, 0, 63))
dr1 = ImageDraw.Draw(overlay)
fnt = ImageFont.load_default()
dr1.text((5, 5), "some text", font=fnt, fill=(255, 255, 255, 160))

img1.paste(overlay, (64, 64), overlay)
img1.show()
img1.save('test.jpg')

Here are hueblock.jpg and test.jpg

hueblock.jpg hueblock with transparent text


Note the arguments to the paste call:

img1.paste(overlay, (64, 64), overlay)

The final argument is an image mask. By supplying an RGBA image as the mask arg its alpha channel is used as the mask, as mentioned in the Pillow docs

[...] If a mask is given, this method updates only the regions indicated by the mask. You can use either “1”, “L” or “RGBA” images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them.

1
votes

You are saving the image file as a JPEG.

JPEGs do not support transparency. In order for your image to have transparency, you must save as a format that supports transparency in the image, such as a PNG.