17

I am using the png package to load PNGs as raster images, and then plotting them. The PNGs are coming from an online source, namely, Wikipedia. I can get the following to work:

library(png)

pngURL <- "http://upload.wikimedia.org/wikipedia/commons/thumb/9/9a/Flag_of_Afghanistan.svg/150px-Flag_of_Afghanistan.svg.png"

# Works:
download.file(pngURL, "temp.png", mode = "wb")
localPNG <- readPNG("temp.png")
plot(1)
rasterImage(localPNG, 0.8, 0.8, 1.2, 1.2)

However, rather than use download.file() to store the PNG locally, then re-loading it, it would be preferable to load the PNG directly from the URL. However, this does not work:

# Does not work:
internetPNG <- readPNG(pngURL)

As it results in

Error in readPNG(pngURL) : 
  unable to open http://upload.wikimedia.org/wiki...

Does anyone have suggestions for how to get this to work, or are there particular reasons that R won't load this PNG from a URL?

Thanks in advance.

isDotR
  • 1,021
  • 2
  • 12
  • 23
  • 1
    Whenever you say "X doesn't work" in a question, tell us more. Do you get an error, in which case post it into the questions. Do you get no errors? In which case why do you think X doesn't work? – Spacedman Oct 15 '12 at 06:51
  • Good point, @Spacedman. Edited the post. – isDotR Oct 15 '12 at 14:15

1 Answers1

21

Use getURLcontent in the RCurl package.

library(RCurl)
myurl <- "http://upload.wikimedia.org/wikipedia/commons/thumb/9/9a/Flag_of_Afghanistan.svg/150px-Flag_of_Afghanistan.svg.png"
my_image <-  readPNG(getURLContent(myurl))
mnel
  • 113,303
  • 27
  • 265
  • 254