Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading PNG files directly from URL

Tags:

r

png

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.

like image 225
isDotR Avatar asked Oct 15 '12 01:10

isDotR


People also ask

How do I load a PNG file?

How to open a PNG file. Nearly all built-in image editing programs can open PNG files. Whether you use a Mac or Windows computer, simply search for the file name and double-click on it. You can then choose the program you want to use from the list of options your computer gives you.

How do I open a PNG file in my browser?

That means if you want to view a PNG file, you simply need to double-click it and it should open in the default viewer on your computer. You can also view a PNG file by dragging it into any web browser (or use CTRL + O to browse for the file and then open it in a browser).

Can HTML load PNG?

You can use PNG, JPEG or GIF image file based on your comfort but make sure you specify correct image file name in src attribute. Image name is always case sensitive.


1 Answers

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))
like image 78
mnel Avatar answered Sep 30 '22 15:09

mnel