Pregunta

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!

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top