How to work with images in python

Official Link: https://pillow.readthedocs.io/en/stable/

In this tutorial, you will learn all you need to know about the P.I.L library

PIL it was created by Fredrik Lundh and Contributors in Python programming and provides support for editing images from code

How to install PIL

If you don't have pillow, install it via pip

pip install pillow

How to open and rotate a image

before rotating
from PIL import Image
#open img_2
with Image.open("img_2.png") as img:
    #rotate image
    img = img.rotate(45)
    #open image in default image viewer
    img.show()
tutorial result - after rotating

How to save an image?


from PIL import Image
#open img_2
with Image.open("img_2.png") as im:
    #rotate image
    im = im.rotate(180)
    #save image instead of opening
    im.save("thumbnail.png","png")

The first param of the save function is the new image name.

The second param of the save function is the image type.

Make sure you use the same extension you use for opening the file.

For example, if you open a png image and you save it as JPEG you will get an error something like this

OSError: cannot write mode RGBA as JPEG
If you want to save the png as jpg for example, you can convert the from PIL import Image

# open img_2
with Image.open("img_2.png") as im:
    im = im.convert('RGB')
    # save image instead of opening
    im.save("thumbnail.jpeg", "jpeg")

Resize an image without keeping the aspect ratio

before resize
Before resizing
from PIL import Image

with Image.open("img_2.png") as img:
    #resize image
    img = img.resize((100,150))
    #open image in default image viewer
    img.show()
before resize
after resizing

Resize an image keeping aspect ratio

You can use the thumbnail method to generate a small image, first parameter is tuplet with the image size. Aspect ration is mainteined

from PIL import Image
#open img_2
with Image.open("img_2.png") as im:
    # generate a thumbnail
    im.thumbnail((100,50))
    #save image instead of opening
    im.save("small.png","png")

How to crop an image


from PIL import Image
#open img_2
with Image.open("img_2.png") as im:
    box= (0,0, 500, 500)
    im  = im.crop(box)
    #save image instead of opening
    im.save("result.png","png")
Box param that is used for the crop method. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. The PIL library uses a Cartesian pixel coordinate system, with (0,0) in the upper left corner. How to read width, height and exif of a image in

from PIL import Image
from PIL.ExifTags import TAGS
#open img_2
with Image.open("img_2.jpg") as img:
    width, height = img.size
    print(width, height)
    getexif = img.getexif()
    for tag_id in getexif:
        # get the tag name
        tag = TAGS.get(tag_id, tag_id)
        data = getexif.get(tag_id)
        # decode bytes
        if isinstance(data, bytes):
            data = data.decode('utf-8')

        print(f"{tag}: {data}")

If you get an error like this UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe4 in position 32: invalid continuation byte try to change the encoding, for example, you can try to use "latin-1" encoding

Create an image on the fly


from PIL import Image

new_width = 200
new_height = 200
new_img = Image.new('RGBA', (new_width, new_height))
new_img.show()

Add a background color


from PIL import Image
new_width = 300
new_height = 60
new_img = Image.new('RGBA', (new_width, new_height))
new_img.paste((0,200,200), [0,0,new_width, new_height//3])
new_img.show()

How to flip an image


from PIL import Image

with Image.open("img_2.png") as img:
    #flip image left to right
    im = img.transpose(Image.FLIP_LEFT_RIGHT)
    #open image in default image viewer
    im.show()
Transpose argument can be PIL.Image.FLIP_LEFT_RIGHT, PIL.Image.FLIP_TOP_BOTTOM, PIL.Image.ROTATE_90, PIL.Image.ROTATE_180, PIL.Image.ROTATE_270, PIL.Image.TRANSPOSE or PIL.Image.TRANSVERSE.

Pasting an image on another image

To paste an image over another image, use the paste method. First, param is the image that is going to be pasted and the second one is a tuplet of the position

from PIL import Image

# basic image, paste the image over this one
with Image.open("logo.png") as img, Image.open("logo_red.png") as overlay_img:
    x = 10
    y = 10
    img.paste(overlay_img, (x, y))


    img.show()

Getting a Histogram of an Image


from PIL import Image

# basic image, paste the image over this one
with Image.open("logo.png") as img:
    #get and print the histogram of the image
    print( img.histogram())

img.show()

Convert an image to black and white


from PIL import Image

# basic image, paste the image over this one
with Image.open("logo.png") as img:
    #get and print the histogram of the image
    img =  img.convert('1',  dither=Image.ADAPTIVE)
    print(img)

img.show()

Read an image pixel by pixel


from PIL import Image

# basic image, paste the image over this one
with Image.open("logo.png") as img:
    img = img.convert('RGB')
    img = img.convert('RGB')
    data = img.getdata()
    for pixel in data:
        print(pixel)

img.show()

Create an image using a mask

image without mask
Image without mask
mask image that will be used for masking
Mask with transparent edge

from PIL import Image

with Image.open("350x350x.png") as img , Image.open('mask.png') as mask, Image.new('RGBA', (img.size[0],img.size[1])) as final_img:


    img = img.convert('RGBA')
    mask = mask.convert('RGBA')

    final_width, final_height = img.size
    mask_width, mask_height = mask.size

    img.thumbnail((final_width, final_height))
    final_img.thumbnail((final_width, final_height))
    # print(img.size)
    print(mask.size)
    # print(final_img.size)
    for y in range(0, final_height -1):
        for x in range(0,final_width -1):

            r, g, b,a = img.getpixel((x,y))
            # make sure the point exist in mask

            if mask_width > x and mask_height > y :

                mask_r, mask_g, mask_b,mask_a = mask.getpixel((x, y))
                # if the mask pixel is not 100% transparent
                if mask_a > 0:
                    # copy the pixel from image, but copy the transparency from mask
                    final_img.putpixel((x, y), (r, g, b,mask_a))

    final_img.show()
image with alpha mask applied
final result

If you have any questions feel free to send me a message via the contact section.

In order to visit this site you must accept the terms and conditions available at this page