Access and download images from urls (which are values of a variable)

Hi everyone, I'm creating a new topic since I couldn't find answers to my question in past publications.

The problem:

One of the variables of my data frame contains urls (one per observation). Each of these url goes directly to an image. I would like to create a loop that allows me to access each of these urls and save the images in a specific folder.

I hope someone can give me some advice to realize that task.


Hey there,

Welcome to the community! It is always much easier to help when you have some code or a minimally reproducible example of your code. I am going to write some dummy code that should get you there.

library(jpeg) #to read and write the images
library(here) #to save the files to the right location - this only works if you're working with a R project

#Code to read one file and save it will look something like this:
myurl <- ""
#Creating temporary place ot save
z <- tempfile()
#Downloding the file
#Reading the file from the temp object
pic <- readJPEG(z)
#Saving to your location
# cleanup

Looped example:

#Looped code 

for (i in 1:100) { #change 100 with your number of rows to read through
  myurl <- paste(df[i,1], sep = "") #you need the exact column number so change 1 to that value and change df to your dataframe's name
  z <- tempfile() #same as above
  pic <- readJPEG(z)
  writeJPEG(pic, paste("image", "i", ".jpg", sep = "") 
#alternatively you can do writeJPEG(pic, here("desired folder", paste("image", "i", ".jpg", sep = ""))
#you can do setwd to the folder you want to write the files but here is much better

Let me know if this helps :slight_smile:


Thanks! This helps a lot

1 Like

Do let me know if this was the solution to your problem :slight_smile:

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.