批量裁剪和调整图像大小以创建缩略图

5
我有一大批jpg图像,想要创建缩略图。这些图像的大小和分辨率各不相同,但我希望所有的缩略图都具有标准尺寸,例如120x80px。然而,我不想拉伸这些图像。因此,我想采取以下步骤:
  1. 将图像裁剪为1.5:1的宽高比。居中裁剪区域(即左右或上下裁剪相等的部分)
  2. 调整图像大小为120 x 80 px。
是否有Linux命令可以这样做?我查看了imagemick convert,但是我无法弄清楚如何进行居中裁剪。似乎您必须手动指定每个图像的裁剪区域?
3个回答

6

这适用于尺寸大于120x80的图像。未在尺寸较小的图像上测试,但您应该能够进行调整。

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

1
这是一个Python脚本crop-resize.py,它可以裁剪、居中和调整输入图像的大小:
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: .)

核心功能是:

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

这与@choroba的bash脚本非常相似。


0

好的,我成功地创建了一些东西,至少对于正方形缩略图来说是有效的。然而,我不太确定如何将其更改为1:5比例的缩略图。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接