ImageMagick 转换多个文件

Al *_*ath 5 command-line imagemagick convert-command

我在一个目录中有 3 个文件:

aaa.jpg    
bbb.jpg  
ccc.jpg  
Run Code Online (Sandbox Code Playgroud)

我可以使用 ImagkMagick convert 缩小图像:

convert aaa.jpg -resize 1200x900 aaa-small.jpg  
Run Code Online (Sandbox Code Playgroud)

我想做目录中的所有图像,例如:

convert *.jpg -resize 1200x900 *-small.jpg  
Run Code Online (Sandbox Code Playgroud)

但这会导致文件命名如下:

*-small-0.jpg  
*-small-1.jpg  
*-small-2.jpg  
Run Code Online (Sandbox Code Playgroud)

我想要的是:

aaa-small.jpg  
bbb-small.jpg  
ccc-small.jpg  
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

ste*_*ver 9

它在文档中令人沮丧地不透明,但是您可以将带引号的shell glob传递给convert(引用以防止 shell 过早地扩展它),并使用Filename Percent Escapes以格式构造输出文件名%[filename:label](其中label是任意用户指定的标签) ,使用输入 basename 转义%[basename]或其旧等效%t

$ ls ???.jpg
aaa.jpg  bbb.jpg  ccc.jpg
Run Code Online (Sandbox Code Playgroud)

然后

$ convert '*.jpg' -set filename:fn '%[basename]-small' -resize 1200x900 '%[filename:fn].jpg'
Run Code Online (Sandbox Code Playgroud)

导致

$ ls ???-small.jpg
aaa-small.jpg  bbb-small.jpg  ccc-small.jpg
Run Code Online (Sandbox Code Playgroud)


sud*_*dus 6

在 for 循环中,可以使用man bash

Parameter Expansion
...
  ${parameter%%word}
      Remove matching suffix pattern.  The word is expanded to produce a pattern just
      as in pathname expansion.  If the pattern matches  a  trailing portion  of the
      expanded  value of parameter, then the result of the expansion is the expanded
      value of parameter with the shortest matching pattern (the ``%'' case) or the
      longest matching pattern (the ``%%'' case) deleted.  If parameter is @ or *,
      the pattern removal operation is applied  to  each positional parameter in turn,
      and the expansion is the resultant list.  If parameter is an array variable
      subscripted with @ or *, the pattern removal operation is applied to each member
      of the array in turn, and the expansion is the resultant list.
Run Code Online (Sandbox Code Playgroud)

以下单行应该完成这项工作

for f in ./*.jpg ; do convert "$f" -resize 1200x900 "${f%.jpg}-small.jpg" ; done
Run Code Online (Sandbox Code Playgroud)

这适用于bash,这是 Ubuntu 的标准 shell。我认为它比 Steeldriver 的优雅方法(只使用convert而不使用for构造)更容易记住。

  • 我建议将文件名从“*.jpg”更改为“./*.jpg”,以防某些名称以“-”开头。 (3认同)
  • +1,因为它遵循 Unix 哲学,即每个工具都应该有效地完成一小部分工作,而不是一个工具可以完成所有工作。 (2认同)