How to locally save an image using Urllib

In this shot, we will discuss how to save an image in Python using Urllib.

Sometimes, it is essential to download image(s), especially when we work on certain projects.

Although we can manually download images, save them to our local drives and use them in the required application, the process can be automated by writing simple Python scripts using the Urllib library.

The Urllib library

Urllib is a standard Python library for accessing websites, downloading and parsing data, POST requests, etc.

Code

Let’s look at the code snippet below.

import urllib.request
import os
# Adding user_agent information
opener=urllib.request.build_opener()
opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36')]
urllib.request.install_opener(opener)
# Image URL and Filename
filename = "pic.jpg"
image_url = "https://cdn.pixabay.com/photo/2016/11/19/14/00/code-1839406_960_720.jpg"
# Get resource
urllib.request.urlretrieve(image_url, filename)
print(os.listdir())

Explanation

  • In line 2, we imported the necessary library.

  • In lines 5 to 7, we added information about the user agent, so downloading the image becomes feasible.

  • In lines 10 and 11, we assigned the image url and the file directory.

  • In line 14, the urllib.request.urlretrieve() function is used to retrieve the image from the given url and store it to the required file directory.

  • In line 16, we printed the files and folders available in the current directory. Here, we can verify that the image has been downloaded and saved locally.

In this way, we can save an image locally by using a URL address using Urllib in Python.