Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

How to locally save an image using requests and shutil libraries

Vinisha Maheshwari

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 requests 
import shutil
import os

# Image URL and filename
image_url = "https://cdn.pixabay.com/photo/2016/11/19/14/00/code-1839406_960_720.jpg"
filename = "pic.jpg"

# Retrieving image without interruptions
r = requests.get(image_url, stream = True)

# Check image 
if r.status_code == 200:
    
    # Preventing the downloaded image’s size from being zero.
    r.raw.decode_content = True
    
    # Open a local file
    with 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())
Using the requests and shutil libraries in Python

Explanation

  • In lines 2 and 3, we import the necessary libraries.

    1. The requests library is used to get an image from the web.
    2. The shutil library is used to save the image locally.
  • In line 6, we declared the url from 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 = True ensures 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_content is set to True, 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 the shutil.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.

RELATED TAGS

communitycreator
python
RELATED COURSES

View all Courses

Keep Exploring