Reputation: 32978
I have a large set of jpg images for which I want to create thumbnails. The images all have different sizes and resolutions, but I would like all thumbnails to have a standard size, e.g. 120x80px. However, I do not want to stretch the images. So I would like to do something of the following:
Is there a linux command to do so? I looked into imagemick convert, but I can't figure out how to do the centered cropping. It seems that you have to manually specify the cropping area for each image?
Upvotes: 5
Views: 3207
Reputation: 414079
Here's a Python script crop-resize.py
that crops, centers, and resizes input images:
usage: crop-resize.py [-h] [-s N N] [-q] [--outputdir DIR]
files [files ...]
Resize the image to given size. Don't strech images, crop and center
instead.
positional arguments:
files image filenames to process
optional arguments:
-h, --help show this help message and exit
-s N N, --size N N new image size (default: [120, 80])
-q, --quiet
--outputdir DIR directory where to save resized images (default: .)
The core function is:
def crop_resize(image, size, ratio):
# crop to ratio, center
w, h = image.size
if w > ratio * h: # width is larger then necessary
x, y = (w - ratio * h) // 2, 0
else: # ratio*height >= width (height is larger)
x, y = 0, (h - w / ratio) // 2
image = image.crop((x, y, w - x, h - y))
# resize
if image.size > size: # don't stretch smaller images
image.thumbnail(size, Image.ANTIALIAS)
return image
It is very similar to the bash script by @choroba.
Upvotes: 1
Reputation: 241748
This works for images larger than 120x80. Not tested on smaller ones, but you should be able to tune it.
#! /bin/bash
for img in p*.jpg ; do
identify=$(identify "$img")
[[ $identify =~ ([0-9]+)x([0-9]+) ]] || \
{ echo Cannot get size >&2 ; continue ; }
width=${BASH_REMATCH[1]}
height=${BASH_REMATCH[2]}
let good_width=height+height/2
if (( width < good_width )) ; then # crop horizontally
let new_height=width*2/3
new_width=$width
let top='(height-new_height)/2'
left=0
elif (( width != good_width )) ; then # crop vertically
let new_width=height*3/2
new_height=$height
let left='(width-new_width)/2'
top=0
fi
convert "$img" -crop "$new_width"x$new_height+$left+$top -resize 120x80 thumb-"$img"
done
Upvotes: 6
Reputation: 32978
Ok I managed create something that works at least for square thumbnails. However, I'm not quite sure how to change this to a 1:5 by 1 thumbnail.
make_thumbnail() {
pic=$1
thumb=$(dirname "$1")/thumbs/square-$(basename "$1")
convert "$pic" -set option:distort:viewport \
"%[fx:min(w,h)]x%[fx:min(w,h)]+%[fx:max((w-h)/2,0)]+%[fx:max((h-w)/2,0)]"$
-filter point -distort SRT 0 +repage -thumbnail 80 "$thumb"
}
mkdir thumbs
for pic in *.jpg
do
make_thumbnail "$pic"
done
Upvotes: 0