MineSweeper
MineSweeper

Reputation: 584

R Downloading Pictures from URL

I have a problem downloading pictures from websites with R. It seems like the image is properly recognized by download.file:

trying URL 'https://i.sstatic.net/Xh9kO.png' Content type 'image/png' length 16592 bytes (16 Kb) opened URL downloaded 16 Kb

And it also is downloaded with the right name and file ending (.png) to the right directory.

download.file("https://i.sstatic.net/Xh9kO.png",paste(**yourDEST**,"Stackoverflow",".png",sep=""))

however, the file is butchered and can't be opened.

What am I doing wrong here?

Upvotes: 3

Views: 2953

Answers (2)

hrbrmstr
hrbrmstr

Reputation: 78792

You can also switch to the httr package:

library(httr)

GET("http://i.imgur.com/pszAeGh.png", 
    write_disk(paste("/tmp/", "Stackoverflow", ".png", sep="")))

A plus of write_disk is that it won't overwrite by default (i.e. you get implicit caching) and no special treatment is required vis-a-vis binary vs text.

Upvotes: 3

Gregor Thomas
Gregor Thomas

Reputation: 145775

I couldn't find a duplicate, so I'll just answer.

The download.file help is a bit fragmented on this, but if you read it all carefully you can find that, on Windows, the default mode = "w" is only suitable for text files. For binary files (pretty much everything but text) you need mode = "wb". This will be done automagically if the URL ends in any of gz, .bz2, .xz, .tgz, .zip, .rda or .RData, however for anything else you need to specify mode = "wb" yourself.

Upvotes: 4

Related Questions