14

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!

Community
  • 1
  • 1
Marc in the box
  • 11,769
  • 4
  • 47
  • 97

2 Answers2

22

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
Mihai Ionescu
  • 968
  • 1
  • 8
  • 13
Thomas
  • 43,637
  • 12
  • 109
  • 140
7

You do NOT have to save the image into the disk. You could directly read the image through the URL as well as below:

library(magick)
image_url <- "http://upload.wikimedia.org/wikipedia/commons/9/95/Apollonian_spheres.jpg"
pic <- image_read(image_url)
print(pic)

enter image description here

ozturkib
  • 1,493
  • 16
  • 28