Download an Image with Python Script

thumbnail

In this tutorial, you will learn how to create script to download an image using Python. Before you begin, you need to import os and requests to read the path is your computer and send a HTTP request to the server.

Example how to download an image with python script

# Created by inpows
# Visit inpows.com for more python tutorials

import os
import requests

# define DownloadImage() with parameter image url
def DownloadImage(imageUrl):

    # sending a HTTP request to the server and
    # saving HTTP response in the response object (req)
    req = requests.get(imageUrl)

    # User will enter image name and path
    imgName = input("\nEnter Name of the Image: ")
    imgPath = input("\nEnter Location Image to Save: ")

    # creating image file with user-input name and path
    imgSave = os.path.join(imgPath, imgName)

    #saving reveived content with png/jpg file in binary format
    with open(imgSave, 'wb') as img:
        # write the contents of the response
        # to the created file in the binary mode.
        img.write(req.content)

    # Printing the successfull message
    print("\nImage Saved in ", os.path.abspath(imgSave))

if __name__ == "__main__" :
    # Prompt user to enter the image url
    imgUrl = str(input("\nEnter Image URL: "))
    DownloadImage(imgUrl)

After you run, you will need to input the image URL, enter name of the image, enter location image to save. You will the output like this:

Enter Image URL: https://www.inpows.com/wp-content/uploads/2018/09/Python.png 

Enter Name of the Image: PythonLogo.png

Enter Location Image to Save: C:\Tutorial Folder

Image Saved in  C:\Tutorial Folder\PythonLogo.png

Read another python tutorial in this website.

Back To Top