How to Download and Save Images in Python

Downloading and saving images (or any other type of file) in Python is a straightforward task when using the requests package to get the data.

 

In this tutorial, we will learn how to download and save images in Python with examples.

 

Import the requests Package

The first step is to import the Python requests package. This package will allow us to make HTTP get requests and store the response as an object.

 

import requests

 

Downloading and Saving an Image

Now we have the requests package imported, we can make an HTTP GET request to the URL of an image before saving the content of the response as an image file using the open() function.

 

import requests

url = 'https://www.skillsugar.com/media/image/parse-json-in-python-1600457348.png'

img = requests.get(url)

with open('test.png', 'wb') as file:
    file.write(img.content)

 

In the above example, we are supplying the URL of an image to the requests.get() method as an argument and storing the response as a variable. Then we are using the open() function in 'wb' (binary write) to create a file object before writing the content of the image to the file test.png using the write() method.

 

Saving The Original File Name

The only reference we have for the original filename of the image is in the URL. One option we have is to use a little bit of RegEx to grab the file name from the URL, store that in a variable and use it as the file name in the open() function.

 

Before using RegEx you will need to import the re package.

 

import re
import requests

url = 'https://www.skillsugar.com/media/image/parse-json-in-python-1600457348.png'

img = requests.get(url)

file_name = re.search('(?:.+\/)([^#]+)', url)

if file_name is None:
    file_name = 'default.png'
else:
    file_name = file_name[1]

with open(file_name, 'wb') as file:
    file.write(img.content)

 

In the above example, we are using an if statement to determine if the result from re.search() is None (no matches found) and setting a default file name. A more robust option might be to generate a name

 

note - The URL of the request is available on the url property of the response object, which may be easier to access in some cases.

 

Conclusion

You now know how to get images and save them to the local file system in Python. As was mentioned at the beginning of the article, the process above will be identical for any type of file, not just images.

image download save