finefoot
finefoot

Reputation: 11272

Difference between `-flatten` and `-alpha Remove` when converting a multi-page PDF into PNGs with ImageMagick

Usually, when I have a PNG file with a transparent background, that I want to turn into a white background instead, I run:

magick input.png -background white -flatten output.png

However, I don't know what to do, when my input file is a PDF file with multiple pages. Because -flatten would merge all those pages into one PNG.

Instead, I tried -alpha Remove:

magick -density 200 input.pdf -background white -alpha Remove -colorspace RGB output.png

According to the docs:

Remove - Composite the image over the background color.

Source: https://imagemagick.org/script/command-line-options.php#alpha

This does work, but it looks worse because the antialiasing seems different.

enter image description here enter image description here enter image description here

The PNG on the left has been extracted from the PDF with the transparent background intact. Afterwards, I ran magick again for each of the pages with -flatten, which resulted in the middle picture. This is what I want the result to look like, but I would have to call magick once for the initial PDF and then many times again for each PNG.

If I use -alpha Remove, the result will look like the image on the right. As you can see, the antialiasing seems different, so edges appear less smooth and the image looks not like it looks in the original PDF.

$ magick --version
Version: ImageMagick 7.1.1-8 Q16-HDRI x86_64 d92cb0e65:20230421 https://imagemagick.org
Copyright: (C) 1999 ImageMagick Studio LLC
License: https://imagemagick.org/script/license.php
Features: Cipher DPC HDRI OpenMP(4.5) 
Delegates (built-in): bzlib djvu fontconfig freetype heic jbig jng jpeg lcms lqr lzma openexr png raqm tiff webp x xml zlib
Compiler: gcc (7.5)

Upvotes: 0

Views: 181

Answers (1)

finefoot
finefoot

Reputation: 11272

With the first method, the initial conversion from PDF to PNG included a colorspace change to RGB. However, during the second call to ImageMagick to flatten the PNGs, ImageMagick automatically changed the colorspace back to sRGB.

The second method had RGB as the final colorspace.

Obviously, changing the colorspace has an effect on the colors and therefore also the shades of gray. The two resulting files of the two methods had different colorspaces and that's what looked like different antialiasing.

Upvotes: 0

Related Questions