[Tex/LaTex] How to convert pgfplots to high quality PNG file with Ghostscript

conversionghostscriptpgfplotspng

Note: This is not a duplicate of How to save a figure produced by tikz save/export as JPG/PNG file. This question deals with Ghostscript and quality concerns. The other question does not deal with Ghostscript, so none of the discussion at the other question is about quality considerations related to Ghostscript. Further, in the comments section, there is a good comment which should be posted as an answer.


Here is my code:

\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}

\begin{axis}[xmin=0, xmax=4, xlabel=x, ylabel=y]
    \addplot[domain=0:4, samples=100, blue, thick] {cos(deg(x))};
\end{axis}

\end{tikzpicture}
\end{document}

When I compile this with pdflatex foo.tex I get a good quality PDF. Here is a screenshot of the PDF:

enter image description here

Now I try to convert the PDF into PNG. Here is my first attempt with -sDEVICE=png16m:

gs -sDEVICE=png16m -sBATCH -sNOPAUSE -r300 -sOutputFile=foo1.png foo.pdf

The output is of pretty disappointing quality. The curve appears to be pixelated. The slopes seem like staircase. It looks like this:

enter image description here

Here is my second attempt with -sDEVICE=pngalpha:

gs -sDEVICE=pngalpha -sBATCH -sNOPAUSE -r300 -sOutputFile=foo2.png foo.pdf

The output is much better but the background is transparent:

enter image description here

My questions:

  1. Why does the png16m device produce so much poorer quality output than pngalpha?
  2. How do you produce good quality images from pgfplots using Ghostscript?

Best Answer

The apparent quality improvement with -sDEVICE=pngalpha as compared to -sDEVICE=pn16m is achieved by application of anti-aliasing.

According to https://www.ghostscript.com/doc/current/Devices.htm#PNG , with -sDEVICE=pngalpha antialiasing is enabled by default:

The pngalpha device is 32-bit RGBA color with transparency indicating pixel coverage. The background is transparent unless it has been explicitly filled. PDF 1.4 transparent files do not give a transparent background with this device. Text and graphics anti-aliasing are enabled by default.

For the png16m output device, antialiasing must be enabled explicitly for text and graphics. Add options -dTextAlphaBits=4 -dGraphicsAlphaBits=4:

-dTextAlphaBits=n
-dGraphicsAlphaBits=n

These options control the use of subsample antialiasing. Their use is highly recommended for producing high quality rasterizations of the input files. The size of the subsampling box n should be 4 for optimum output, but smaller values can be used for faster rendering. Antialiasing is enabled separately for text and graphics content.