9

I'm trying to convert a pdf plot to a png or jpeg file. The reason is that I want to use the images for presentations and I need both formats, having exactly the same dimensions/scaling.

I tried the function im.convert() in the animation package, but the output looks really bad, in both png and jpeg.

To be able to run the following code you need the "animation" package and the ImageMagick software (http://www.imagemagick.org/script/convert.php)

library("animation")
ani.options(outdir = getwd())

pdf("bm.pdf")
plot(1:10)
dev.off()

im.convert("bm.pdf", output = "bm.jpeg")
im.convert("bm.pdf", output = "bm.png")
aymer
  • 199
  • 2
  • 2
  • 9
  • 1
    The normal way would be to simply safe in the desired format from the code that created the graph. There are much better tools for converting PDF to PNG, e.g., use ImageMagick directly and not from R. To get better results from ImageMagick you need to adjust options. – Roland Sep 04 '13 at 15:22
  • How are you dealing with the fact that the external application you're using to generate presentation materials may well scale different image types differently? – Carl Witthoft Sep 04 '13 at 17:16
  • [This question](https://stackoverflow.com/questions/26232103/save-a-plot-as-png-and-pdf-only-by-one-call-to-the-plot-function-in-r?rq=3) has answers covering the "normal way [...] to simply safe in the desired format from the code that created the graph" proposed by @Roland – jan-glx Jul 20 '23 at 18:24

1 Answers1

15

The result of im.convert is probably not satisfactory because it uses the default resolution, which is 74 dpi. You can increase the resolution by passing an extra parameter:

im.convert("bm.pdf", output = "bm.png", extra.opts="-density 150")

-density 150 will double the resolution and your PNGs and JPEGs will look nicer.

But in general it is probably better to use png() and jpeg() to generate the plots and use appropiate parameters to get the same results as with pdf(). For example:

pdf(width=5, height=5)
plot(1:10)
dev.off() 

png(width=5, height=5, units="in", res=150) 
plot(1:10)
dev.off()
f3lix
  • 29,500
  • 10
  • 66
  • 86