Download and view images from an url using python

In this article we shall see how to download or view images from a url using python pillow. Downloading the images does not require any external libraries. But, we need pillow in order to view the images.

Let us get started with the installation of the pillow package. If you only need to download the image, skip this installation part.

Installation

Pillow can be installed using the pip in python.

pip install pillow

Viewing the images from a URL

Let us see how to just show the image from the URL using the pillow package. Make sure that the URL is the path to the image itself and not to the webpage containing the image.

This is how the URL to the image looks like.

https://miro.medium.com/max/1400/1*X40IVMQsIgSjWsGAxJG7Zw.jpeg

Note that the URL has the extension at the end, which indicates that this is the direct path to the image.

Running this code snippet will show us the image as we have called the show() function from pillow. This image will pop up in our screen.

showing image from url

How it works?

  1. The get method from the requests library gets the response from the url.
  2. The content object will have bytes data of the image.
  3. With the help of the BytesIO we are writing this bytes data to a temporary file in memory.
  4. With pillow we open this temporary image and display it using the show() method.

Saving the images

Saving the images are even more simple, compared to showing them. Saving or downloading the images does not require any external libraries.

The following code snippet shows you how to save the image using python.

That is all we need to download an image from the URL.

How it works?

  1. The content object will have bytes data of the image.
  2. Give the name of the file and the mode as “wb” (write bytes) as the arguments to the open method.
  3. The write method will write the bytes data to the file.

Hope this article was useful. Feel free to ask questions.

Happy coding !