Coding Triumph

Helpful code snippets & tutorials

How to download an image from a URL using python

When it comes to downloading images from the web with Python, there are three major modules we can use: wget, urllib, and requests. Being the most popular HTTP client for Python, we’ll be using the requests module in this tutorial. It’s beginner-friendly and has a convenient API that makes downloading any type of file an easy process. Let’s see how to do that in few simple steps

Prerequisite:

1. Install the requests module:

Requests is a third-party module, so we need to install it first:

pip install requests

2. Import the required modules:

# to request the image from the web
import requests
# to save the image locally
import shutil

3. Store the image URL into a variable:

image_url = "https://cdn.pixabay.com/photo/2017/06/05/07/58/butterfly-2373175_960_720.png"

4. Sent a GET request to the image URL:

When downloading files from the web, it’s preferable to opt for streaming responses, especially for large files. It downloads files in chunks, it’s memory efficient, keeps the connection alive, and guarantees no interruptions. To that end, we need to set the stream flag to True.

req = requests.get(image_url, stream = True)

5. Retrieve the image a save it to a local file:

If the response was successful, we can save the image to a local file with the help of the shutil module.

if req.status_code == 200:
    # "Response.raw" by default will not decode compressed responses with gzip and deflate encodings, so you will need to do this manually.
    req.raw.decode_content = True
    # save the image in binary mode.
    with open('my_image.png','wb') as file:
        # "shutil.copyfileobj" will assemble all the response chunks into a single file
        shutil.copyfileobj(req.raw, file)
        
    print('Image downloaded successfully')
else:
    print('Image Couldn\'t be retrieved')

The full script:

Putting it all together, the finished script should look something like this:

# import the required modules
import requests 
import shutil

# store image URL in a variable
image_url = "https://cdn.pixabay.com/photo/2017/06/05/07/58/butterfly-2373175_960_720.png"

# send a GET request to the image URL
req = requests.get(image_url, stream = True)

# if the image was retrieved successfully
if req.status_code == 200:
    # decode the response
    req.raw.decode_content = True
    # save the image as local file in binary mode.
    with open('my_image.png','wb') as file:
        shutil.copyfileobj(req.raw, file)
        
    print('Image downloaded successfully')
else:
    print('Image Couldn\'t be retrieved')
If you like this post, please share
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments