Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to directly read an image file from a url address in R

Tags:

url

r

jpeg

I'm trying to directly load a .jpeg image from a url address. I'm wondering if there is a basic way to do this by using a url connection.

I first tried:

require(biOps)
con <- url("http://upload.wikimedia.org/wikipedia/commons/9/95/Apollonian_spheres.jpg")
pic <- readJpeg(con)
#Error in readJpeg(con) : Cannot open file.

This other question seems to be along the same lines, but for a .png file. I tried to adapt to a .jpeg, but also got an error.

require(biOps)
require(RCurl)
myurl <- "http://upload.wikimedia.org/wikipedia/commons/9/95/Apollonian_spheres.jpg"
pic <-  readJpeg(getURLContent(myurl))
#Error in readJpeg(getURLContent(myurl)) : Cannot open file.

Any help would be greatly appreciated!

like image 364
Marc in the box Avatar asked Jul 29 '13 07:07

Marc in the box


People also ask

How do I pull an image from a URL?

Right-click on the image and select Copy Image Link from the menu that opens. Paste the address into a new email, text editor, or new browser window. Another option in most browsers is to open the image in a new tab or window, and then copy the address from the URL bar of the browser.

How do I import URL data into R?

To import data from a web site, first obtain the URL of the data file. Click on the “Import Dataset” tab in Rstudio and paste the URL into the dialog box. Then click “OK”. After you hit “OK” you will get another dialog box.


1 Answers

Just save the image as a temporary file:

myurl <- "http://upload.wikimedia.org/wikipedia/commons/9/95/Apollonian_spheres.jpg"
z <- tempfile()
download.file(myurl,z,mode="wb")
pic <- readJPEG(z)
file.remove(z) # cleanup
like image 117
Thomas Avatar answered Oct 21 '22 06:10

Thomas