DEV Community

Sidhartha Mallick
Sidhartha Mallick

Posted on

Random Cropping/Scaling Images to Fit the Required Specs or Dimensions for Any kind of Uploads

A simple Python Script with ffmpeg would do wonders.

import os

def generate_ffmpeg_command_scale(path, w, h):
    input_path = path.split('/')
    output_path = '/'.join(input_path[:-1]) + '/out-' + input_path[-1];
    ffmpeg_cmd = 'ffmpeg -i {} -vf scale={}:{} {}'.format(path, w, h, output_path);
    return ffmpeg_cmd

def generate_ffmpeg_command_crop(path, w, h):
    input_path = path.split('/')
    output_path = '/'.join(input_path[:-1]) + '/out-' + input_path[-1];
    ffmpeg_cmd = 'ffmpeg -i {} -vf crop={}:{}:0:0 {}'.format(path, w, h, output_path);
    return ffmpeg_cmd

WIDTH = int(input("width = "));
HEIGHT = int(input("height = "))
PATH = input("path = ")

scale_command = generate_ffmpeg_command_scale(PATH, WIDTH, HEIGHT)
crop_command = generate_ffmpeg_command_crop(PATH, WIDTH, HEIGHT)
print(scale_command);
print(crop_command);

os.system(scale_command);
Enter fullscreen mode Exit fullscreen mode

Let’s go through the script, _what is does ? How it does ?
_
This script accepts 3 parameters, the expected dims (HxW) and the path to the file in the local system. You can get the path to the file by simply dragging the file into the terminal and copy the path that appears.

The generate_ffmpeg_command() function generates the command for processing the image and specifies the output location of the file to the dame directory but changes the filename as out-<filename> .

The function returns the command requires and the os module in python executes the shell command in your terminal and gets you the requires image.

The scale parameter of the ffmpeg command scales your input image to the required dimensions.

Try it on replit.com :

Image description

Advanced Modifications :

  1. To crop the image uniformly from the middle, just replace the scale parameter by crop, that would be enough for it.

  2. To crop the image from the top-left corner, update line no. 6 to : ffmpeg_cmd = ffmpeg -i {} -vf crop={}:{}:0:0 {}'.format(path, w, h, output_path);

mail me at: mallicksidhartha7@gmail.com , for any kind of customisations, be it Image Processing, Video Processing, Cropping, Compression or so using ffmpeg.

!! Happy Coding !! 😋

Top comments (0)