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

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:

Quick Solution

Short on time? Here’s a one-paragraph answer:

To download an image in Python, import the requests library and pass the URL of the image into the requests.get(url) function to get a response object from the server. Its response.content attribute gets you the binary image content. Finally, use the open() and write() functions to write the binary content to a new file.

Here’s the quick code solution:

import requests

url = "https://example.com/image.jpg"
response = requests.get(url)

with open("image.jpg", "wb") as f:
    f.write(response.content)

Preparation and Library Installation

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.request.urlretrieve()

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

Thanks β™₯️

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

Feel free to check out our free email academy here:

Good Luck & Happy Coding!


Image Sources.