Skip to content

Instantly share code, notes, and snippets.

@cprima
Created June 9, 2024 17:32
Show Gist options
  • Save cprima/17411e0c88b204ea8e09bc7a83edc99c to your computer and use it in GitHub Desktop.
Save cprima/17411e0c88b204ea8e09bc7a83edc99c to your computer and use it in GitHub Desktop.
image crop from center

Image Processing Script

This Bash script processes PNG images in the current directory. It renames images that are already 1600x900 with a _1600x900.png suffix. For images that are larger, it crops them to 1600x900 from the center and saves them with the same suffix.

Requirements

Installation

To install ImageMagick on Ubuntu, run:

sudo apt-get update
sudo apt-get install imagemagick

Usage

  1. Save the script to a file, e.g., process_images.sh.

  2. Make the script executable:

    chmod +x process_images.sh
  3. Find the dimensions of all png files in the directory:

    for file in *.png; do
      identify -format "%f: %wx%h\n" "$file"
    done
  4. Adjust the dimensions in the script

  5. Run the script in the directory containing your PNG files:

    ./process_images.sh
  6. cleanup

    find . -maxdepth 1 -type f -name "*.png" ! -name "*_1600x900.png" -print0 | xargs -0 rm

Script Details

The script performs the following actions:

  1. Iterates over all .png files in the current directory.
  2. Checks the dimensions of each file using identify from ImageMagick.
  3. If the image is 1600x900, it renames the file by appending _1600x900.png.
  4. If the image is larger, it crops the image to 1600x900 from the center using convert from ImageMagick and saves it with the _1600x900.png suffix.

Example

Given the following files in the directory:

006_inspect-testcase-arguments.png: 1600x900
007_eplore-test-explorer.png: 1600x900
008_adjust-InvokeWorkflow-arguments_WRONG.png: 1626x926

After running the script, the directory will contain:

image1_1600x900.png
image2_1600x900.png (cropped from 1920x1080)
image3_1600x900.png

Author

Christian Prior-Mamulyan cprior@gmail.com

License

This script is released under the Creative Commons Attribution 4.0 International License (CC-BY)

#!/bin/bash
for file in *.png; do
dimensions=$(identify -format "%wx%h" "$file")
if [[ $dimensions == "1600x900" ]]; then
mv "$file" "${file%.png}_1600x900.png"
else
convert "$file" -gravity center -crop 1600x900+0+0 "${file%.png}_1600x900.png"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment