How to merge a transparent png image with another image using PIL

from PIL import Image background = Image.open(“test1.png”) foreground = Image.open(“test2.png”) background.paste(foreground, (0, 0), foreground) background.show() First parameter to .paste() is the image to paste. Second are coordinates, and the secret sauce is the third parameter. It indicates a mask that will be used to paste the image. If you pass a image with transparency, then … Read more

In Python, how do I read the exif data for an image?

You can use the _getexif() protected method of a PIL Image. import PIL.Image img = PIL.Image.open(‘img.jpg’) exif_data = img._getexif() This should give you a dictionary indexed by EXIF numeric tags. If you want the dictionary indexed by the actual EXIF tag name strings, try something like: import PIL.ExifTags exif = { PIL.ExifTags.TAGS[k]: v for k, … Read more

Combine several images horizontally with Python

You can do something like this: import sys from PIL import Image images = [Image.open(x) for x in [‘Test1.jpg’, ‘Test2.jpg’, ‘Test3.jpg’]] widths, heights = zip(*(i.size for i in images)) total_width = sum(widths) max_height = max(heights) new_im = Image.new(‘RGB’, (total_width, max_height)) x_offset = 0 for im in images: new_im.paste(im, (x_offset,0)) x_offset += im.size[0] new_im.save(‘test.jpg’) Test1.jpg Test2.jpg … Read more

How to convert a PIL Image into a numpy array?

You’re not saying how exactly putdata() is not behaving. I’m assuming you’re doing >>> pic.putdata(a) Traceback (most recent call last): File “…blablabla…/PIL/Image.py”, line 1185, in putdata self.im.putdata(data, scale, offset) SystemError: new style getargs format but argument is not a tuple This is because putdata expects a sequence of tuples and you’re giving it a numpy … Read more

How do I resize an image using PIL and maintain its aspect ratio?

Define a maximum size. Then, compute a resize ratio by taking min(maxwidth/width, maxheight/height). The proper size is oldsize*ratio. There is of course also a library method to do this: the method Image.thumbnail. Below is an (edited) example from the PIL documentation. import os, sys import Image size = 128, 128 for infile in sys.argv[1:]: outfile … Read more