3

I'm trying to use this this approach to add a semi-transparent polygon to an image. The problem is the image is a JPEG. I know that JPEGs don't have an alpha channel, so I was hoping there was a way I could have PIL take in a JPEG, convert it to a form which has an alpha channel, add the semi-transparent mask, then merge the mask with the image and convert it back into a JPEG for saving. Can PIL accomplish this? If not, how else might I go about doing this? Thanks!

Community
  • 1
  • 1
Jenny Shoars
  • 994
  • 3
  • 16
  • 40

1 Answers1

7

That's easy. Just paste the jpeg into a new rgba Image():

#!/usr/bin/env python3

from PIL import Image
from PIL import ImageDraw

im = Image.open("existing.jpg")
logo = Image.open("python-32.png")

back = Image.new('RGBA', im.size)
back.paste(im)
poly = Image.new('RGBA', (512,512))
pdraw = ImageDraw.Draw(poly)
pdraw.polygon([(128,128),(384,384),(128,384),(384,128)],
          fill=(255,255,255,127),outline=(255,255,255,255))

back.paste(poly, (0,0), mask=poly)
back.paste(logo, (im.size[0]-logo.size[0], im.size[1]-logo.size[1]), mask=logo)

back.show()

This additionally adds a png (with transparency) to the image.

TNT
  • 3,392
  • 1
  • 24
  • 27
  • Great job! Can I have a question? I just used your code (without `logo`) and I found that I had to use `png` if I want to save `back` (`jpg` will invoke an error). However, the size of `back` is 5 times lager than the original image. Do we have a way to minimize the size of `back`? – Yves Aug 07 '17 at 02:06
  • @Yves Can't reproduce what you describe. When I replace `back.show()` with `back.save('back.jpg', 'JPEG')`, the image gets saved as expected. Maybe you should open a new question with full error description.(You could add a comment then that begins with @tnt so I will get notified.) – TNT Aug 07 '17 at 15:11
  • https://stackoverflow.com/questions/45558282/pil-cant-save-the-jpg-pasted-with-a-png – Yves Aug 08 '17 at 02:15
  • Appears to be a new feature introduced by new minor version to fail: after upgrading my `pillow 4.1.1` to `4.2.1` I also get the exception (solution in the answer to the new [question](https://stackoverflow.com/a/45558382/1547831)). – TNT Aug 08 '17 at 14:28