[Tutor] Pasting an image with transparency

Peter Otten __peter__ at web.de
Fri Jun 2 09:31:11 EDT 2017


Terry wrote:

> Slackware 14.2 64-bit
> Python 2.7.13
> 
> I am trying to automate some photo processing by pasting a
> sig or watermark. The sig image is a .png with transparency
> but when it pastes it does so with a black background. Is there
> a way to paste with transparency?
> 
> 
> 
> from PIL import Image
> from PIL import ImageEnhance
> 
> fname = "sample.jpg"
> 
> im = Image.open(fname)
> print(im.format, im.size, im.mode)
> 
> out = im.resize((1068, 712))
> 
> enh = ImageEnhance.Sharpness(out)
> enh = enh.enhance(2.5)
> 
> sig =
> Image.open("/home/tvbare/pics/recent_pics/sigs/opi_sig_landscape.png")
> print(sig.format, sig.size, sig.mode)
> box = (768, 616, 1018, 662)
> enh.paste(sig, box)
> 
> enh.show()
> 

We read the docstring so you don't have to ;)

>>> from PIL import Image
>>> image = Image.open("sample.jpg") # some random pic I have lying around
>>> help(image.paste)
Help on method paste in module PIL.Image:

paste(im, box=None, mask=None) method of PIL.JpegImagePlugin.JpegImageFile 
instance

[...]    
    Note that if you paste an "RGBA" image, the alpha band is
    ignored.  You can work around this by using the same image as
    both source image and mask.
[...]

So let's try that. (Since I don't have a transparent picture handy I'm using 
a copy of <https://raw.githubusercontent.com/python-pillow/Pillow/master/Tests/images/transparent.png>.)

>>> stamp = Image.open("transparent.png")
>>> image.paste(stamp, (0, 0), mask=stamp)
>>> image.show()

Seems to work...




More information about the Tutor mailing list