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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With