Introduction

Working with images in Python gives you a variety of development capabilities, from downloading images with an URL to retrieving photo attributes.

In this article, we’ll rehearse several different methods want to download images in Python.

Prerequisites

To fully enjoy this post, you ought to have the following:

  1. Some experience with Python 2 or Python 3.
  2. Python 3 installed on your local machine. There’s one script compatible with Python 2 within the Urllib Package section.

1.) Using the Requests Package

Being the foremost popular HTTP client in Python, the Requests package is elegant and straightforward to use for beginners. Many developers consider it a convenient method for downloading any file type in Python.

Assuming you’ve got Python 3 installed to your local environment, create a directory mkdir download-images-python and add during a requests_python_img_dl.py. Once that file is opened, install and import the subsequent packages:

import requests #request img from web import shutil #save img locally

Once you’ve imported those files, create a url variable that’s set to an input statement posing for the image URL.

url = input('Please enter a picture URL (string):') #prompt user for img url

Additionally, create another variable also set to an input statement, file_name:

url = input('Please enter an image URL (string):') #prompt user for img url

In the next line of code, implement the get() method from the requests module to retrieve the image. The tactic will absorb two parameters, the URL variable you created earlier, and stream = True by adding this second argument to guarantee no interruptions will occur when the tactic is running.

res = requests.get(url, stream = True)

The copyfileobj() method to write down your image because the file name, builds the file locally in binary-write mode and saves it locally with shutil. Although it isn’t necessary, it’s good to see if the image was retrieved successfully using Request’s Status Code during a conditional statement.

<code class="language-python" data-lang="python">if res.status_code == 200:
    with open(file_name,'wb') as f:
        shutil.copyfileobj(res.raw, f) 
    print('Image sucessfully Downloaded: ',file_name)
else:
    print('Image Couldn\'t be retrieved')

Your finished script should look something like this:

<code class="language-python" data-lang="python">import requests # request img from web
import shutil # save img locally

url = input('Please enter an image URL (string):') #prompt user for img url
file_name = input('Save image as (string):') #prompt user for file_name

res = requests.get(url, stream = True)

if res.status_code == 200:
    with open(file_name,'wb') as f:
        shutil.copyfileobj(res.raw, f) 
    print('Image sucessfully Downloaded: ',file_name)
else:
    print('Image Couldn\'t be retrieved')

Execute your script by running the subsequent command in your terminal:

<code class="language-python" data-lang="python">python requests_python_img_dl.py

Your downloaded images will save to the newly created download-images-python directory.

2.) Downloading Images Using urllib

Another favored method for downloading data in Python is thru urllib, a package that collects several modules for working with URLs, including:

urllib.request for opening and reading.
urllib.parse for parsing URLs.
urllib.error for any exceptions raised by urllib.request.
urllib.robotparser for parsing robot.txt files.

If urllib isn’t present in your current environment, install it by executing the code below:

pip install urllib

Once you’ve got urllib installed, create a replacement directory for your project, mkdir python-image-downloads. This step doesn’t have to be repeated if you already created it within the previous section. Within that directory create an images folder, also as a dl_img.py file. Navigate to your dl_img.py file, and at the highest insert the subsequent line of code to import the urllib package:

import urllib.request

import urllib.request

With your module imported, your task is to form a user-friendly script that will allow you to download images quickly and arranged. First, create a url variable from an input function:

url = input('Please enter image URL (string):')

Then decide what you’d like your image file to save lots of as, using another input statement:

file_name = input('Save image as (string):')

With these two variables that hold the info needed to download and organize your newly created image files, write the code that saves the image(s). Begin by defining a function that takes in three parameters, your url variable, the designated file_path you’d wish to save the image to, and therefore the file_name set previously.

def download_image(url, file_path, file_name):

Inside the function create a full_path to where the image goes to be saved. The image’s full path is going to be the file_path with the file_name concatenated, and a ’.jpeg’ string added to the top. 

def download_image(url, file_path, file_name):

To create the code that really downloads the image, you will need to integrate the urllib.request and URL retrieved which can automatically download and save the image supporting the arguments given.

def download_image(url, file_path, file_name): full_path = file_path + file_name + '.jpg' urllib.urlretrieve(url, full_path)

Call that function at the top of your script that ought to like almost like this:

import urllib.request

def download_image(url, file_path, file_name):
    full_path = file_path + file_name + '.jpg'
    urllib.urlretrieve(url, full_path)

url = input('Please enter image URL (string):')
file_name = input('Save image as (string):')

download_image(url, 'images/', file_name)

When you call download_image you will need to undergo three arguments again, At this point it’ll be your URL, the file path which is that the ‘images/‘ folder you created within the beginning, and therefore the file_name you chose. As long as you’re in your python-image-downloads directory, run your script in your terminal with the code below:

python dl_img.py

If you’ve not yet upgraded Python 3 you’ll end up receiving several errors regarding urllib.request, the subsequent code should be compatible with Python 2.

import urllib2

def download_image(url):
    request = urllib2.Request(url)
    img = urllib2.urlopen(request).read()
    with open (file_name + '.jpg', 'w') as f: f.write(img)

url = input('Please enter image URL (string):')
file_name = input('Please enter file name (string):')

download_image(url)

3.) Wget Module

In addition to the Requests and Urllib packages, it is also possible to download images in Python by employing the wget module. If you’ve already made your python-image-download navigate inside, if not create it now. Within the directory create a wget_img_dl.py file and import the wget module like so:

import wget

Once you’ve got wget installed and imported, set a url variable adequate to an input statement that assigns a picture address:

url = input('Please enter image URL (string):')

Utilizing wget.download pass within the url variable as an argument and set it adequately to a file_name variable you will be ready to access it afterward.

<code class="language-python" data-lang="python">file_name = wget.download(url)

print('Image Successfully Downloaded: ', file_name)

The full script should like on the brink of this:

<code class="language-python" data-lang="python">import wget

url = input('Please enter image URL (string):')

file_name = wget.download(url)

print('Image Successfully Downloaded: ', file_name)

Now you’ll run your script 

python wget_img_dl.py

Conclusion

As always, each of those methods carries pros and cons. If you’ve got problems installing the Requests package or want fewer dependencies in your program, urllib could be your best choice. However, the Requests module has become a well-liked and reliable way of downloading anything in Python, with even the urllib documentation recommending it as a high-level HTTP client interface.

Was this post helpful?