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

Sidhartha Mallick
2 min readJan 3, 2022

--

“If you don’t find the tools you need, better create them”

A simple Python Script with ffmpeg would do wonders.

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 :

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 !!

--

--

Sidhartha Mallick

Associate Software Engineer@Gojek, Ex- Intern@BrowserStack