如何使用imagemagick旋转目录中的所有图像?

Mic*_*ant 21 shell-script imagemagick image-manipulation wildcards

我想旋转与模式匹配的目录中的所有图像。

到目前为止,我有:

for file in `ls /tmp/p/DSC*.JPG`; do
  convert $file -rotate 90 file+'_rotated'.JPG
done
Run Code Online (Sandbox Code Playgroud)

但这没有输出?

ter*_*don 20

您的代码有很多问题。首先,您正在解析 ls 这是一个坏主意。您还需要$file像您指出的那样引用该变量,并且还应该引用它,这样它就不会中断空格。您正在声明,num但从未使用过。更安全的方法是:

find /tmp/p/ -name "DSC*.JPG" | while IFS= read -r file; do
  convert "$file" -rotate 90 "$file"_rotated.JPG
done
Run Code Online (Sandbox Code Playgroud)

如果您的文件包含换行符,这仍然会出现问题,但如果您的路径包含空格,则至少不会中断。

如果文件都在同一目录中,则可以使用 globbing 进一步简化。您还可以使用参数扩展来创建foo_rotated.JPG1而不是foo.JPG_rotated.JPG

for file in /tmp/p/DSC*.JPG; do
  convert "$file" -rotate 90 "${file%.JPG}"_rotated.JPG
done
Run Code Online (Sandbox Code Playgroud)

  • 您的方法将创建`original_filename.JPG_rotated.JPG"`。添加`"${file%.JPG}"_rotated.JPG` 会更合适,恕我直言。干杯! (2认同)

小智 18

mogrify -rotate 90 *.jpg 使用imagemagick旋转所有图像的更好的 One-Liner

mogrify -rotate 90 /tmp/p/DSC*.JPG 实际上将在目录中旋转所有.JPG开始DSCp

Mogrify(imagemagick 的一部分)不同于Convert它修改原始文件 http://www.imagemagick.org/script/mogrify.php


Val*_*ami 11

使用PE(参数扩展)的一种简单方法是

for f in /tmp/p/DSC*.JPG
do
  convert -rotate 90 "$f" "${f%.JPG}"_converted.JPG
done
Run Code Online (Sandbox Code Playgroud)

  • 应该注意的是,其中没有任何特定的“bash”,它是完美标准的 POSIX sh 语法。 (2认同)

小智 7

不是 imagemagic 解决方案,但

sips -r 90 *.JPG
Run Code Online (Sandbox Code Playgroud)

将以 .JPG 结尾的所有图像旋转 90 度。这是一个很好的一个班轮。


Mar*_*rco 6

不解析lsls这里不需要。此外,您应该引用您的变量,以防它们包含空格。

for file in *.JPG; do
  convert -rotate 90 "$file" rotated_"$file"
done
Run Code Online (Sandbox Code Playgroud)