DEV Community

Cover image for Crop a picture automatically with a fixed ratio - Python example
FlyNestor
FlyNestor

Posted on

Crop a picture automatically with a fixed ratio - Python example

There is a large number of occasions where you have to crop a picture selected by the user of a website.

I have already made an article on how to manually crop a picture with JavaScript.

In this article I will show how to automatically crop a picture with Python in the back-end. This code allows automatic video creation from a text and a picture on my website rollideo.com.

In this example the cropped picture will have a fixed ratio of 16:9. The user can choose a picture of any ratio as an input. The output will always be 16:9.

I have decided to offer a centered crop as a first option because usually the most interesting part of a picture is in the center. A more sophisticated code can detect faces or other parts in a picture. You can also add the option to crop on one specific corner or other crop possibilities.

#This code will automatically crop the picture to a ratio of 16:9.
from PIL import Image

with Image.open(path_file_temp) as image:
    width, height = image.size
    if width/height == 16/9:
        if width != 1280:
            image_crop = image.resize((1280, 720))
        else:
            image_crop = image
    elif width/height > 16/9:
        offset  = int(abs(width-16/9*height)/2)
        image_crop1 = image.crop([offset,0,width-offset,height])
        image_crop = image_crop1.resize((1280, 720))
    else:
        offset  = int(abs(9/16*width-height)/2)
        image_crop1 = image.crop([0,offset,width,height-offset])
        image_crop = image_crop1.resize((1280, 720))

    file_source = random_id + '.png'
    path_file_crop = os.path.join(UPLOAD_FOLDER, file_source)              
    image_crop.save(path_file_crop, format="png")


Enter fullscreen mode Exit fullscreen mode

A warning about Pillow
Pillow is using External Libraries to process the different format of images (.jpg .png .webp etc).

To test the image processing code, you have to make a test with all the format of image that you want to allow. If Image.open failed it's probably because there is some missing external libraries.

For more details, see the Pillow installation guide.

Once the tests are done with the different formats allowed, you should list the allowed image format in the user guide, and also add warning messages "The image format X is not supported".

Top comments (0)