以 N 为模调整大小

Resize modulo N

我有各种高度的图片,需要将它们调整为最接近的高度模数 N。

示例:

原文件:

1200x956

我需要h%N = 0 with N = 20。那么预期的输出是:

1200x960

因为 960%20 = 0.

谢谢。

这可以通过一个简单的 脚本来解决。例如,采取以下逻辑流程。

  • 迭代所有图像的列表
  • 捕获当前图像宽度
  • 虽然不是 20 的模数
    • 如果模数超过 10 则递增
    • 模数递减量小于10
    • 根据需要重复
  • mogrify 调整宽度值的原始图像。
files="first_image.jpg second_image.jpg"

for file in $files
do
    # Capture original width
    let width=$(identify -format '%w' $file)
    # Identify offset
    let offset=$(expr $width % 20)
    # Repeat until offset is 0
    while [ $offset -ne 0 ]
    do
        # Increment/Decrement width as needed
        if [ $offset -lt 10 ]
        then
            width=$(($width-1))
        else
            width=$(($width+1))
        fi
        # Update offset
        offset=$(expr $width % 20)
    done
    # Overwrite image with newly found width
    mogrify -resize ${width}x $file
done

编辑

当然上面的例子可以简化。甚至可以算出expr $width % 20.

的评价
files="first_image.jpg second_image.jpg"

delta() {
    mod=$(expr  % 20)
    [[ $mod -lt 10 ]] && echo $(expr $mod \* -1) || echo $(expr 20 - $mod)
}

for file in $files
do
    let width=$(identify -format %w $file)
    let height=$(identify -format %h $file)
    let new_width=$(($width + $(delta $width)))
    let new_height=$(($height + $(delta $height)))
    mogrify -resize "${new_width}x${new_height}" $file
done