Search code examples
rpng

Why can't I view or open downloaded PNG file from URL


I have downloaded an image (in fact several images using a for loop) using the below code. However, these images are not opening up, though they seem to have got downloaded completely. In fact these images are not opening up in plain Photo editor or Paint etc., tools. Appreciate inputs and what shall be done..

Below is the code that I tried with for loop:

p <- c("http://assets.pokemon.com/assets/cms2/img/pokedex/full/001.png",
       "http://assets.pokemon.com/assets/cms2/img/pokedex/full/002.png",
       "http://assets.pokemon.com/assets/cms2/img/pokedex/full/003.png",
       "http://assets.pokemon.com/assets/cms2/img/pokedex/full/003_f2.png",
       "http://assets.pokemon.com/assets/cms2/img/pokedex/full/004.png")
p

for (url in p)
  download.file(url, destfile=file.path("C:/Users/xyz/Desktop/test",basename(url)))

library(imager)
# loading only first image for viewing
i <- load.image("C:/Users/xyz/Desktop/test/001.png")
plot(i)

Then I just downloaded a single file giving a simple destination name and tried to load and display using the below code.

download.file("http://assets.pokemon.com/assets/cms2/img/pokedex/full/001.png", 
              destfile=file.path("C:/Users/xyz/Desktop/test","first_img.png"))

i_s <- load.image("C:/Users/xyz/Desktop/test/first_img.png")
plot(i_s)

In both the cases I am getting the below error message.

Error in read.bitmap(file) : 
  File f: C:/Users/xyz/Desktop/test/001.png does not appear to be a PNG, BMP, JPEG, or TIFF

Same way, if I try to open the downloaded images using Photos, Photos editor, Adobe, Paint etc., I get similar messages like format not supported, unable to load photo, etc., messages. However, note that if I simply copy and paste the image url in the browser, the image appears perfectly in the web page.

Appreciate inputs on what can be done here.


Solution

  • Loos like you have to set mode = "wb" in download.file. The manual says:

    The choice of binary transfer (‘mode = "wb"’ or ‘"ab"’) is important on Windows, since unlike Unix-alikes it does distinguish between text and binary files and for text transfers changes ‘\n’ line endings to ‘\r\n’ (aka ‘CRLF’).

    On Windows, if ‘mode’ is not supplied (‘missing()’) and ‘url’ ends in one of ‘.gz’, ‘.bz2’, ‘.xz’, ‘.tgz’, ‘.zip’, ‘.jar’, ‘.rda’, ‘.rds’ or ‘.RData’, ‘mode = "wb"’ is set so that a binary transfer is done to help unwary users.

    So for the single file try:

    download.file("http://assets.pokemon.com/assets/cms2/img/pokedex/full/001.png", 
                  destfile=file.path("C:/Users/vsvas/Desktop/test","first_img.png"),
                  mode = "wb")