DEV Community

Cover image for Make image Instagram compatible using Python
Ashutosh Sharma
Ashutosh Sharma

Posted on • Edited on

Make image Instagram compatible using Python

Image processing is quite easy and fast in Python with libraries available. I recently was trying to make images Instagram-friendly using Python script.

What do I mean Instagram Friendly Images:

Basically, Instagram supports all kinds of images ( https://help.instagram.com/1631821640426723) but a square-shaped photo fits the best.

So, We have to resize the photo to a 1080 x 1080 pixels size.

Output File Size

There are multiple use cases are possible like

  1. The original photo is already square but smaller in size.
    Use case 1

  2. The original photo is a rectangle and smaller in size
    Use case 2-1

Use Case 2-1

  1. The original photo is already square but larger in size.
    Use case 3

  2. The original photo is a rectangle and larger in size.

Use case 4-1

So the idea here is to use the maximum space from the original image only but if there is an area remaining fill it with a color.

Use Case 4-2

We will use the Pillow (Python’s image manipulation library) to process the image. If not install use below command


pip install Pillow

Enter fullscreen mode Exit fullscreen mode
from PIL import Image
import requests


def make_square(im, min_size=1080, fill_color=(0, 0, 0, 0)):
    x, y = im.size
    print("Original size "+str(x)+" X "+str(y))
    size = max(min_size, x, y)
    new_im = Image.new('RGB', (size, size), fill_color)    
    if(x > y):
        mod = size/x
        x = int(x * mod)
        y = int(y * mod)
    elif(x < y):
        mod = size/y
        x = int(x * mod)
        y = int(y * mod)

    new_im.paste(im.resize((x,y)), (int((size - x) / 2), int((size - y) / 2)))
    x, y = new_im.size
    print("New size "+str(x)+" X "+str(y))
    return new_im



def processImage(url):
    img = Image.open(requests.get(url, stream=True).raw)
    new_img = make_square(img)
    new_img.show()


processImage("https://images.pexels.com/photos/771742/pexels-photo-771742.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1")
Enter fullscreen mode Exit fullscreen mode

Original Image:
Original Image

Resized Image:
Resized Image

It will return the squared image.

Happy Coding <3

Top comments (0)