5 Easy Ways to Download an Image from a URL in Python

Rate this post

Problem Formulation and Solution Overview

In this article, you’ll learn how to download an image from the web in Python.

To make it more fun, we have the following running scenario:

Sven, a Journalist from Greeland, is writing about Glacier Calving. His editor would like photos of iceberg collapses in the area accompanying his article. Unfortunately, Sven is not tech-savvy and needs your help.

💬 Question: How would we write Python code to perform image downloads?

We can accomplish this task by one of the following options:


Preparation

Before our code executes successfully, two (2) new libraries will require installation.

  • The requests library is used to send and receive HTTP requests.
  • The pillow (pil) library is used to retrieve and process images.

To install these libraries, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install requests

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install pillow

Hit the <Enter> key on the keyboard to start the installation process.

If the installations were successful, a message displays in the terminal indicating the same.


Feel free to view the PyCharm installation guide for the required libraries.

Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import requests
from PIL import Image
import shutil
import urllib

💡 Note: The additional libraries indicated above do not require installation as they come built-in to Python.


Method 1: Use requests.get() and write

The requests.get() function is used with file open() and write() to download and save the specified file.

img_url = 'https://blog.finxter.com/wp-content/uploads/2022/04/greenland_01a.jpg'
response = requests.get(img_url)
if response.status_code:
    fp = open('greenland_01a.png', 'wb')
    fp.write(response.content)
    fp.close()

The above code attempts to connect to the stated URL (img_url). If successful, a Status Code of 200 is returned. This image is then opened and written to the specified file and saved to the current working directory.

Output


Method 2: Use requests.get and Image()

The requests library is used with the pil library’s open() and requests.get() functions to download and save the specified file.

img_url = 'https://blog.finxter.com/wp-content/uploads/2022/04/greenland_02a.jpg'
img = Image.open(requests.get(img_url, stream = True).raw)
img.save('greenland_02a.png')

The above code connects to the stated URL (img_url). This image is then opened and written in raw format to img. Finally, it is saved to the current working directory as an image file.

Output


Method 3: Use requests.get and shutil

The requests library is used with the shutil and requests.get() functions to copy, download and save the specified file.

img_url = 'https://blog.finxter.com/wp-content/uploads/2022/04/greenland_03a.jpg'
response = requests.get(img_url, stream=True)
with open('greenland_03a.png', 'wb') as out_file:
    shutil.copyfileobj(response.raw, out_file)
del response

This code retrieves the specified URL, then opens and creates a file object. This object saves the file stated in open() to the current working directory. To clean up, the response object is removed.

Output


Method 4: Use urllib

This code uses the urllib and requests libraries to connect, retrieve, process, and save the image. For example, we call urllib.request.urlretrieve(img_url, "greenland_04a.png") to download the image at the given URL.

Here’s the full example:

img_url = 'https://blog.finxter.com/wp-content/uploads/2022/04/greenland_04a.jpg'
urllib.request.urlretrieve(img_url, "greenland_04a.png")

On one line of code, this code calls the requests and urllib libraries to perform all the tasks to retrieve, process, and save the indicated image to the current working directory.

Output


Bonus:

This code grabs all the URLs above and pastes them to a List. Next, the List is referenced in a For loop. Finally, each image is retrieved, processed, and saved to the current working directory.

import urllib
import requests

imgs = ['https://blog.finxter.com/wp-content/uploads/2022/04/greenland_01a.jpg',
        'https://blog.finxter.com/wp-content/uploads/2022/04/greenland_02a.jpg',
        'https://blog.finxter.com/wp-content/uploads/2022/04/greenland_03a.jpg',
        'https://blog.finxter.com/wp-content/uploads/2022/04/greenland_04a.jpg']

icount=1
for i in imgs:
    urllib.request.urlretrieve(i, f'greenland_0{str(icount)}b.png')
    icount += 1

Summary

These four (4) methods of downloading and saving images should give you enough information to select the best one for your coding requirements.

Good Luck & Happy Coding!


Image Sources.