Categories
Python Answers

How to download image using Python requests library?

Spread the love

Sometimes, we want to download image using Python requests library.

In this article, we’ll look at how to download image using Python requests library.

How to download image using Python requests library?

To download image using Python requests library, we can use the requests.get method to make a GET request.

Then we call shutil.copyfileobj to save the file to disk.

For instance, we write:

import requests
import shutil

url = 'https://i.picsum.photos/id/926/200/300.jpg?hmac=jlGQWyYJAmrBGxcsX5Uwr_J1N3bMHU46d3660T6emao'
path = 'photo.jpg'

r = requests.get(url, stream=True)
if r.status_code == 200:
    with open(path, 'wb') as f:
        r.raw.decode_content = True
        shutil.copyfileobj(r.raw, f)

We define the url to get the image from and the path to save the image to.

Then we call requests.get with the url and stream set to True to make the request.

Then if r.status_code is 200, then we call open to open the file path with 'wb' permission to write the file to the path whether it exists or not.

Then we set r.raw.decode_content to True to decode the file content.

And finally, we call shutil.copyfileobj with r.raw to save the content to file f.

Now we should see the photo displayed when we open photo.jpg.

Conclusion

To download image using Python requests library, we can use the requests.get method to make a GET request.

Then we call shutil.copyfileobj to save the file to disk.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *