How to Download Images with Python

José Fernando Costa
2 min readOct 27, 2019

--

Ever wanted to download some images, but wish you knew how to do it programmatically? Well, today I want to show you how to do it, with Python and the handy requests and Pillow libraries.

For starters, you need to get both libraries installed. For that, just run the usual pip install command, pip install requests and pip install pillow, respectively. In case you’re on Windows like me, don’t forget to run the command line as Administrator, otherwise you won’t be able to install the libraries.

Since the script as a whole is quite short, I’ll show you right away the complete code gist, and then take you step by step:

Complete Python script to download images

We start by importing the necessary libraries:

import requests
from PIL import Image
from io import BytesIO

Then, we create two variables which are used for readability’s sake: url holds the URL for the target image, and file_name holds the name to be used for the file which will be saved in the computer.

In case you’re not familiar with the split() method, it separates a string (url) into a list of smaller strings, split at the occurrences of the specified delimeter (a slash in this case). Then, we pick the last string from that list, in this case, EdAGGFS.jpg, which includes both the original file name and its extension. The syntax [-1] is the Python syntax to pick the element at the last index of a list.

Then, the last three lines of code are the actual meat of this script.

img_request = requests.get(url) is responsible for making an HTTP GET request for the image.

BytesIO(img_request.content) takes the content of the GET request and parses it into an in-memory binary stream. Then, theImage.open()part is responsible for opening that stream as an Image of the Pillow library. In a less technical way, think of it as using the binary data of the GET request to be opened as an image by Pillow.

Finally, the img.save(file_name) line takes the Pillow Image and saves it as an actual file in your computer, using the name and extension we had defined in the file_name variable (which is the original name and extension of the image).

And that’s pretty much it. Now you’re ready to download any images from the web using Python!

--

--

José Fernando Costa
José Fernando Costa

Written by José Fernando Costa

Documenting my life in text form for various audiences

No responses yet