17

My goal is to download an image from an URL and then display it in R.

I got an URL and figured out how to download it. But the downloaded file can't be previewed because it is 'damaged, corrupted, or is too big'.

y = "http://upload.wikimedia.org/wikipedia/commons/5/5d/AaronEckhart10TIFF.jpg"
download.file(y, 'y.jpg')

I also tried

image('y.jpg')

in R, but the error message shows like:

Error in image.default("y.jpg") : argument must be matrix-like 

Any suggestions?

user3768495
  • 4,077
  • 7
  • 32
  • 58

3 Answers3

28

If I try your code it looks like the image is downloaded. However, when opened with windows image viewer it also says it is corrupt. The reason for this is that you don't have specified the mode in the download.file statement.

Try this:

download.file(y,'y.jpg', mode = 'wb')

For more info about the mode is see ?download.file

This way at least the file that you downloaded is working.

To view the image in R, have a look at

jj <- readJPEG("y.jpg",native=TRUE)
plot(0:1,0:1,type="n",ann=FALSE,axes=FALSE)
rasterImage(jj,0,0,1,1)

or how to read.jpeg in R 2.15 or Displaying images in R in version 3.1.0

Community
  • 1
  • 1
MichaelVE
  • 1,304
  • 10
  • 15
  • Thanks! It works now. An follow up question: what should i do if I don't want to download (save) the jpeg file on the disk but just save it to the workplace? – user3768495 Mar 18 '15 at 16:46
  • You can download the image as a temporary file. Please accept the first answer if this answers your original question – MichaelVE Mar 19 '15 at 07:28
  • After adding the arg `mode = 'wb'`, it works. Thanks. – Jiaxiang Jun 11 '19 at 11:00
2

this could work too here

library("jpeg")

library("png")

x <- "http://upload.wikimedia.org/wikipedia/commons/5/5d/AaronEckhart10TIFF.jpg"    

image_name<- readJPEG(getURLContent(x)) # for jpg

image_name<- readPNG(getURLContent(x)) # for png
Community
  • 1
  • 1
jatin singh
  • 123
  • 1
  • 1
  • 13
1

After downloading the image, you can use base R to open the file using your default image viewer program like this:

file.show(yourfilename)
Tania
  • 136
  • 1
  • 4