2

I have so many different images in a directory with sequential names 1 2 3 4 ... I was wondering if it was possible to convert all of them to jpg and resize them all to 900x900 without preserving aspect ratio.

What I tried for the first part is:

$ mogrify -format jpg -- *

But when I do this memory usage increases so quickly and then the process in killed. What I tried for resizing is:

$ 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.

As I've said the names of the files are sequential numbers. I also have the following:

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

So What is the problem? How can I fix it?

Zanna
  • 72,312

1 Answers1

6

I'd recommend using the convert tool from ImageMagick:

convert input.png -resize 900x900 output.jpg

The -resize option should be pretty obvious and the output file format is automatically determined using its filename extension.

To run this on all files in the current directory, try this:

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

This will take all files fromt he current directory (no matter the file type), and for each input file create the respective output file name by stripping the old extension and adding ".jpg" instead. Then it uses convert as described above to resize and convert the image, which creates a new file and leaves the original as it is. If that was successful (&&), check if the output file exists and if the input file name is different from the output file name (e.g. if one of the original files already was a jpg). Now if these conditions are met, we assume we can delete the input file.

Byte Commander
  • 110,243