Download image from a link using R

62 Views Asked by At

I have a question regarding downloading an image from a link for example this one: https://shaarolami-query.customs.mof.gov.il/CustomspilotWeb/en/PreRuling/Home/GetPicture?requestNumber=2023900009118 Whenever I try to download the image the file cannot be opened. I am not sure if it is related to the programs that I have or the codes that I used.

Here is the different codes that I used:

ua_firefox <- "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0"

for (i in seq_along(df$ImgSrc)) {
  link <- paste0("https://shaarolami-query.customs.mof.gov.il", df$ImgSrc[i])
  file_name <- df$CustomsItem[i] 
  print(file_name)
  download_path <- file.path(download_directory, file_name)
  print(i)
  print(download_path)
  download.file(link, download_path, headers = c("User-Agent" = ua_firefox), mode = "wb")
}
for (i in seq_along(df$ImgSrc)){
  link <- paste0("https://shaarolami-query.customs.mof.gov.il", df$ImgSrc[i])
  response_link <- GET(link)
  img_links <- c(img_links, link)
  file_name <- df$CustomsItem[i]
  if (http_status(response)$status == 200) {
    image_content <- content(response, "raw")
    
    writeBin(image_content, paste0(file_name, ".jpg"))
    cat("Image downloaded and saved as 'image.jpg'\n")
  } else {
    cat("Failed to download the image.\n")
  }

  download_path <- file.path(download_directory, file_name)
  
  download.file(link, download_path, mode = "wb")
}
image_url <- "https://shaarolami-query.customs.mof.gov.il/CustomspilotWeb/en/PreRuling/Home/GetPicture?requestNumber=2023900009118"

tryCatch({
  response <- GET(image_url)
  
  if (http_status(response)$status == 200) {
    image_content <- content(response, "raw")
    
    writeBin(image_content, "image.jpg")
    cat("Image downloaded and saved as 'image.jpg'\n")
  } else {
    cat("Failed to download the image. Status code: ", http_status(response)$status, "\n")
  }
}, error = function(e) {
  cat("An error occurred: ", conditionMessage(e), "\n")
})

All of these downloaded the images but in the end I could not open the downloaded image. I would really appreciate if you can help me. Thank you in advance!

0

There are 0 best solutions below