I would like to batch resize and convert to jpg a few png files. But some pixels are transparent, and some are half transparent; I would like the transparent ones to be white, and the half-transparent ones to be white half mixed with color.

I have two half solutions:

convert file.png -resize 1200x1200  -background white -flatten  file.jpg

which works well, but only for one file; so is there an easy way to batch the "convert" command? I want my files to keep their names, which are not numbered (img001.png, img002.png, etc.) but descriptive (room.png, horse.png, etc.)... Or:

mogrify -resize 1200x1200 -format jpg -background "#FFFFFF" *.png

which batches well, but the half-transparent pixels are full color, which is pretty ugly when a line is supposed to fade into alpha; is there a way to fix this?

  • Can mogrify not use the -flatten option, then? – evilsoup Jan 20 '16 at 17:03
  • oh, it works. I didn't know that's what it was for. Thanks! – Fal Jan 20 '16 at 18:05
  • mogrify and convert are both programs from the ImageMagick project. There may be some exceptions, but generally they have the same options. – evilsoup Jan 20 '16 at 18:17

You could use a for loop:

for f in ./*.png; do convert "$f" -resize -background white -flatten "${f%.*}.jpg"; done

This will operate on every file with a name ending in .png in the current directory. Each go around on the loop, the matched filename is read into the variable $f; in order to massage this information into the output filename, the above command uses parameter substitution.

${var%Pattern} -- Remove from $var the shortest part of $Pattern that matches the back end of $var.

${var%%Pattern} -- Remove from $var the longest part of $Pattern that matches the back end of $var.

  • thanks for the explanation, batch naming is tricky! I'll use the other answer, it's simpler, but this could help me later. – Fal Jan 20 '16 at 18:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.