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:
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:
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:
My questions:
- Why does the
png16mdevice produce so much poorer quality output thanpngalpha? - How do you produce good quality images from
pgfplotsusing Ghostscript?



gsyou can play with the resolution set via the-r ...option. – AlexG Sep 03 '18 at 12:53gs -sDEVICE=png16m -sBATCH -sNOPAUSE -r300 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -sOutputFile=foo1.png foo.pdf– David Purton Sep 03 '18 at 13:13-rsetting for both thegscommands I have mentioned but I get very different outputs. Why is that? Why is it that choosingpng16mas the device leads to inferior results than choosingpngalpha? – Lone Learner Sep 03 '18 at 14:59-sDEVICE=pngalpha. Can you elaborate in an answer why-dTextAlphaBits=4 -dGraphicsAlphaBits=4improves the output? – Lone Learner Sep 03 '18 at 15:01-sDEVICE=pngalphais accomplished through antialiasing, that is, setting a blended colour in the step corners. – AlexG Sep 03 '18 at 15:08png16mdoes not perform antialiasing? I was expecting bothpng16mandpngalphato perform similar antialiasing. The only difference I was expecting between them is the presence or lack of alpha channel. But it appears thatpng16mandpngalphawork very differently. – Lone Learner Sep 03 '18 at 15:51-densityoption to your needs. – Stefan Pinnow Sep 06 '18 at 11:07