DEV Community

Sidhartha Mallick
Sidhartha Mallick

Posted on

2 2

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 !! πŸ˜‹

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay