Bash:如果宽度/高度超过特定值,则批量调整图像大小

问题描述 投票:0回答:2

如果输入图像宽度或高度超过特定值(Linux 或 Mac OS X,命令行),有没有办法批量调整图像大小?

我在这里发现了一个类似的问题,但该问题仅针对一张图像。

bash imagemagick
2个回答
3
投票

一个可能的解决方案:

#!/bin/sh

set -e
maxwidth="1900"  # in pixels, the widest image you want to allow.

#find all .jpg in current dir and subdirectories
FILES="$(find . -iname '*.jpg')"

for imagefile in $FILES
do
if [ -f "$imagefile" ]; then
imgwidth=`sips --getProperty pixelWidth "$imagefile" | awk '/pixelWidth/ {print $2}'`
else
    echo "Oops, "$imagefile" does not exist." 
    exit
fi

if [ $imgwidth -gt $maxwidth ]; then
    echo " - Image too big. Resizing..."
    sips --resampleWidth $maxwidth "$imagefile" > /dev/null 2>&1  # to hide sips' ugly output 
    imgwidth=`sips --getProperty pixelWidth "$imagefile" | awk '/pixelWidth/ {print $2}'`
    imgheight=`sips --getProperty pixelHeight "$imagefile" | awk '/pixelHeight/ {print $2}'`
    echo " - Resized "$imagefile" to $imgwidth""px wide by $imgheight""px tall";
fi
done

2
投票

使用 ImageMagick 套件中的

mogrify
可能:

mogrify -resize 1024x768\> *.jpg

按比例缩小所有超过 1024x768 的 jpeg 大小。首先在图像的副本上尝试一下。添加

-path output
将结果写入名为
output
的子目录 - 首先使用
mkdir output

尾随的

>
指定仅在尺寸超过给定值时缩小图像 - 来自 https://imagemagick.org/script/command-line-processing.php#geometry:

widthxheight> 缩小尺寸大于相应宽度和/或高度参数的图像。

尾部斜杠前面有一个反斜杠,因此 (bash) shell 不会将其视为

stdout
到文件的重定向。

© www.soinside.com 2019 - 2024. All rights reserved.