curl to download images from URLs provided by connected input blocks, then utilizes ImageMagick’s convert command to crop each image to specified dimensions. This approach is particularly useful when you need to process multiple images with the same cropping parameters.
Here it is in action in Hunch: Crop an image
Detailed Explanation
Let’s break down the script and examine its key components:Configuration Variables
CROP_WIDTHandCROP_HEIGHT: Define the size of the cropped areaCROP_XandCROP_Y: Define the starting point (top-left corner) of the cropOUTPUT_FORMAT: Specifies the format of the output images
Processing Input Blocks
hunch input: This command retrieves all input data for the Code Runner block in JSON format.jq -r '.blocks[] | .files[] | .url': This complexjqcommand processes the JSON:.blocks[]: Iterates through all input blocks.files[]: For each block, it accesses the ‘files’ array.url: Extracts the URL of each file- The
-roption outputs raw strings without quotes
Downloading and Cropping Images
curl -fsSL "$url": Downloads the image from the URL-f: Fails silently on server errors-s: Silent mode-S: Shows error messages-L: Follows redirects
|: Pipes the downloaded image data directly to ImageMagickconvert -: ImageMagick command to process the image (’-’ reads from stdin)-crop ${CROP_WIDTH}x${CROP_HEIGHT}+${CROP_X}+${CROP_Y}: Crops the image using the specified dimensions and starting point/output/cropped-$i.$OUTPUT_FORMAT: Saves the cropped image to the output directory with a numbered filename
Incrementing the Counter
i, ensuring each output file has a unique name.
Error Handling
While this script doesn’t include explicit error handling, it uses some best practices:- The
-fflag incurlwill cause the script to fail if an image can’t be downloaded - Using
set -eat the beginning of the script (not shown here) would cause it to exit on any command failure
Output
The script saves cropped images to the/output directory, which is accessible to downstream blocks in your Hunch workflow. Each image is named cropped-N.png, where N is a number starting from 1.
This script demonstrates the power of combining Hunch’s Code Runner with standard Unix tools and ImageMagick to perform complex image processing tasks. It can be easily modified to perform other image manipulations by changing the ImageMagick commands.