Alpha removal with ImageMagick is bad but only with a white background

image manipulationimagemagick

I'm getting surprising (to me) variations in antialiasing quality when converting a PDF (with black text on white only) to a PNG and removing transparency with ImageMagick (version 6.7.7.10 from Ubuntu 14.04).

My sample input file is the result of running pdflatex on

\documentclass[preview]{standalone}
\begin{document}
Hello, world!
\end{document}

At 300 dpi, the result is horrible (that's with a white background, adding -background \#ffffff or -background white produces visually indistinguishable output):

convert -density 300 -alpha remove -alpha off a.pdf 300-white.png

-density 300

There's some anti-aliasing, but not very good, and some lines (such as the horizontal stroked on the e) have completely disappeared.

Choosing any color other than white produces a decent result.

convert -density 300 -background \#fffffe -alpha remove -alpha off a.pdf 300-fffffe.png

-density 300 -background #fffffe

Curiously, the rendering is better at low resolutions (while still not ideal) — at least the text is readable.

convert -density 100 -alpha remove -alpha off a.pdf 90-white.png

-density 100

At higher resolutions, the rendering is still clearly poor, but at least the lines start to appear.

convert -density 750 -alpha remove -alpha off a.pdf a.png

-density 750

  • Why is antialiasing so bad for black on white, and perfectly fine with any other background color, even if that background color is visually indistinguishable from white?
  • If I set this up as part of an automated process where someone won't be around to visually inspect the result, what parameters do I need to avoid to get good results?

Best Answer

It is like when background is white, ImageMagick detects that there are only two colors — black and white — and switches to a grayscale mode of PNG, hence the ugly result:

enter image description here

To limit the ugliness of applying black and white to anti-aliased edges, you can disable anti-aliasing with +antialias:

convert -density 300 -alpha remove -alpha off +antialias a.pdf 300-white.png

enter image description here

So now, how to prevent using the grayscale mode of PNG? Here it is:

convert -density 300 -alpha remove -alpha off a.pdf png24:300-white-24.png

enter image description here

Related Question