如何将目录中的所有图像转换为jpg?

yuk*_*say 2 resize mogrify imagemagick image-processing

我在一个目录中有这么多不同的图像,它们的名称1 2 3 4 ...是连续的,我想知道是否可以在jpg不保留纵横比的情况下将它们全部转换为 900x900并将它们调整为 900x900。

我在第一部分尝试的是:

$ mogrify -format jpg -- *
Run Code Online (Sandbox Code Playgroud)

但是当我这样做时,内存使用量增加得如此之快,然后进程被杀死。 我尝试调整大小的是:

$ mogrify -resize 900x900 -- *
mogrify: insufficient image data in file `109.jpg' @ error/jpeg.c/ReadJPEGImage/1039.
mogrify: no decode delegate for this image format `' @ error/constitute.c/ReadImage/501.
mogrify: no decode delegate for this image format `' @ error/constitute.c/ReadImage/501.
mogrify: no decode delegate for this image format `' @ error/constitute.c/ReadImage/501.
mogrify: no decode delegate for this image format `' @ error/constitute.c/ReadImage/501.
Run Code Online (Sandbox Code Playgroud)

正如我所说,文件的名称是序列号。我还有以下几点:

$ file * | grep -Po "^\d*: *\K[^:,]*(?=,)" | sort | uniq
ASCII text
GIF image data
JPEG image data
PNG image data
Run Code Online (Sandbox Code Playgroud)

那么问题是什么?我该如何解决?

Byt*_*der 6

我建议使用convertImageMagick的工具:

convert input.png -resize 900x900 output.jpg
Run Code Online (Sandbox Code Playgroud)

-resize选项应该非常明显,并且输出文件格式是使用其文件扩展名自动确定的。

要对当前目录中的所有文件运行此命令,请尝试以下操作:

for inputfile in ./* ; do
    outputfile="${inputfile%.*}.jpg"
    convert "$inputfile" -resize 900x900 "$outputfile" &&
    [[ -e "$outputfile" && "$inputfile" != "$outputfile" ]] && rm "$inputfile"
done
Run Code Online (Sandbox Code Playgroud)

这将从当前目录中获取所有文件(无论文件类型如何),并通过剥离旧扩展名并添加“.jpg”来为每个输入文件创建相应的输出文件名。然后它使用convert如上所述来调整图像大小和转换图像,这会创建一个新文件并保持原始文件不变。如果成功 ( &&),请检查输出文件是否存在以及输入文件名是否与输出文件名不同(例如,原始文件之一是否已经是 jpg)。现在如果满足这些条件,我们假设我们可以删除输入文件。