How to locally save an image using requests and shutil libraries
In this shot, we will discuss how to locally save an image using the requests and shutil libraries in Python.
Sometimes downloading image(s) becomes essential, especially when we are working on certain projects. Although we can manually download images, save them to our local drives, and use them in the required application, the process can be automated by writing simple Python scripts.
The requests library in Python is mostly used for downloading any type of file using Python, and the shutil library is used to save the file locally.
Code
import requestsimport shutilimport os# Image URL and filenameimage_url = "https://cdn.pixabay.com/photo/2016/11/19/14/00/code-1839406_960_720.jpg"filename = "pic.jpg"# Retrieving image without interruptionsr = requests.get(image_url, stream = True)# Check imageif r.status_code == 200:# Preventing the downloaded image’s size from being zero.r.raw.decode_content = True# Open a local filewith open(filename,'wb') as f:shutil.copyfileobj(r.raw, f)print('Image successfully Downloaded: ',filename)else:print('Image Couldn\'t be retrieved')print(os.listdir())
Explanation
-
In lines 2 and 3, we import the necessary libraries.
- The
requestslibrary is used to get an image from the web. - The
shutillibrary is used to save the image locally.
- The
-
In line 6, we declared the
urlfrom which the image is downloaded. -
In line 7, the file directory in which the image needs to be downloaded needs to be mentioned along with the image name, i.e., filename +
image_name.jpg. If no filename is mentioned, the picture gets downloaded in the same directory as that of the Python script file. -
In line 10, we used the
get()method to retrieve the image from the specified URL.stream = Trueensures no interruptions during image retrieval. -
In lines 13 to 24, we check if the image is retrieved successfully. In either case, a message of success or failure is printed.
-
In line 16, the value of
decode_contentis set toTrue, which ensures the downloaded image’s size will not be zero. -
In lines 19 and 20, we open a local file with
wb(write binary) permission. Now, we create a file in binary-write mode locally and use theshutil.copyfileobj()function to write our image to the file. -
In lines 22 to 24, we print the success/failure message.
-
In line 26, we just print the files and folders available in the current directory. Here, we can verify that the image has been downloaded and saved.