Manipulating Images using Python

Manipulating Images using Python

5 min read

Say you are doing internship at freshlybuilt.com and freshlybuilt admin give you the boring job of resizing thousands of images and adding a small logo watermark to the corner of each. Doing this with a basic graphics program such as Paintbrush or Paint would take forever. A fancier graphics application such as Photoshop can do batch processing, but that
software costs hundreds of dollars. Let’s write a script to do it instead.

So to do this task we will use PIL (Python Imaging Library) which is very powerful.

Below is the test image in which we will add the freshlybuilt logo in bottom right corner. Result is also shown in below image.

STEP -1 => OPEN THE LOGO IMAGE

import os    
from PIL import Image

SQUARE_FIT_SIZE = 4000
LOGO_FILENAME = 'logo.png'

logoIm = Image.open(LOGO_FILENAME).convert("RGBA")
logoWidth, logoHeight = logoIm.size

In the above code snippet we imported the os and Image (from PIL). After this we take the masking size i.e. square-fit-size for final image export equals to 4000 (you can change it according to your need.). We named freshlybuilt logo as ‘logo.png‘ and opened this image using open method and convert it into RGBA format to avoid masking errors. Also, we store the logo image width and height into variables as mentioned above.

STEP – 2 => LOOP OVER ALL FILES AND SELECT IMAGES

os.makedirs('withLogo', exist_ok=True)
# Loop over all files in the working directory.
for filename in os.listdir('.'):
    if not (filename.endswith('.png') or filename.endswith('.jpg')) \
    or filename == LOGO_FILENAME:
        continue # skip non-image files and the logo file itself
    
    im = Image.open(filename).convert("RGBA")
    width, height = im.size

Now we will make a directory with name of ‘withLogo’ using os module (Note :- exist_ok = True, is for that condition when directory is present then it will not generate any errors). After this we will iterate over each files in current working directory and open that file that have ‘.png’ and ‘.jpg’ extension and skip our logo file.

STEP – 3 => RESIZE THE IMAGES

# Check if image needs to be resized.
if width > SQUARE_FIT_SIZE and height > SQUARE_FIT_SIZE:
# Calculate the new width and height to resize to.
    if width > height:
        height = int((SQUARE_FIT_SIZE / width) * height)
        width = SQUARE_FIT_SIZE
    else:
        width = int((SQUARE_FIT_SIZE / height) * width)
        height = SQUARE_FIT_SIZE
    # Resize the image.
    print('Resizing {}...'.format(filename))
    im = im.resize((width, height))

Now in the above code snippet if our opened image dimensions is greater than square fit size then we will resize it relative to square fit size. That is the reason why i take square fit size value large because we don’t want to change the pixels of our original image. For images with small dimensions this step can save your time.

STEP – 4 => ADD LOGO AND SAVE THE IMAGE

# Add the logo.
print('Adding logo to {}...'.format(filename))
im.paste(logoIm, (width - logoWidth, height - logoHeight), logoIm)
# Save changes.
im.save(os.path.join('withLogo', filename))

In the last step we will add the logo to the image by using paste option of Image. Also don’t forget to note that we have to specify the dimension where we want to add the logo. So the second parameter specify the dimension to understand this see the below image. After this we will save the changes in the ‘withLogo’ folder as same filename.

SO AFTER GETTING THIS SO FAR WE HAVE COMPLETED OUR BASIC SMALL PROJECT WHICH CAN PROCESS THOUSANDS OF IMAGES IN A MINUTE.

COMPLETE CODE :-

import os
from PIL import Image

SQUARE_FIT_SIZE = 4000
LOGO_FILENAME = 'logo.png'

logoIm = Image.open(LOGO_FILENAME).convert("RGBA")
logoWidth, logoHeight = logoIm.size

os.makedirs('withLogo', exist_ok=True)
# Loop over all files in the working directory.
for filename in os.listdir('.'):
    if not (filename.endswith('.png') or filename.endswith('.jpg')) \
    or filename == LOGO_FILENAME:
        continue # skip non-image files and the logo file itself
    
    im = Image.open(filename).convert("RGBA")
    width, height = im.size
    # Check if image needs to be resized.
    if width > SQUARE_FIT_SIZE and height > SQUARE_FIT_SIZE:
    # Calculate the new width and height to resize to.
        if width > height:
            height = int((SQUARE_FIT_SIZE / width) * height)
            width = SQUARE_FIT_SIZE
        else:
            width = int((SQUARE_FIT_SIZE / height) * width)
            height = SQUARE_FIT_SIZE
        # Resize the image.
        print('Resizing {}...'.format(filename))
        im = im.resize((width, height))
        
        # Add the logo.
    print('Adding logo to {}...'.format(filename))
    im.paste(logoIm, (width - logoWidth, height - logoHeight), logoIm)
    # Save changes.
    im.save(os.path.join('withLogo', filename))

Hope You like my first article on freshlybuilt. You can also follow me on linkedin. And in last, thanks to everyone who read this article till last.

Choose your Reaction!
Leave a Comment