SoFunction
Updated on 2025-04-11

Use Python to download and save network pictures

introduction

Today we will learn a simple and interesting Python project: download pictures from the Internet and save them to your computer! You don't need to have programming experience, this article will teach you step by step in the easiest way.

Project Objectives

Download an online picture

Show pictures on your computer

Save the picture to local file

Preparation

We need to use two Python libraries:

Pillow (PIL): Used to process pictures.

Requests: Used to obtain data from the Internet.

If you haven't installed them yet, you can run the following command in the terminal:

pip install pillow requests

Code decomposition and explanation

We divide the code into several simple parts.

1. Load pictures from the network

This function is responsible for loading the image from the specified URL and returning an image object.

from PIL import Image
import requests
from typing import Optional

def load_image_from_url(url: str) -> Optional[]:
    """
    From the specifiedURLLoad the image and return the image object。

    parameter:
        url (str): Picture ofURLaddress。

    return:
        Optional[]: If loading successfully,return图片对象;否则return None。
    """
    try:
        # Get image data from URL        with (url, stream=True) as response:
            response.raise_for_status()  # Check whether the request is successful            return ()
    except  as e:
        print(f"Error in network request: {e}")
    except IOError as e:
        print(f"Image processing error: {e}")
    return None

Key points:

We use : to obtain image data and to automatically manage resources with.

If there is a network problem, raise_for_status() will throw an error to help us discover the problem.

Convert image data into image objects that can be processed.

2. Save the picture to the local area

This function saves the image to the path you specified.

def save_image(image: , file_path: str) -> None:
    """
    Save the image to the specified path。

    parameter:
        image (): Image object to save。
        file_path (str): Save the path。
    """
    try:
        (file_path)
        print(f"The image has been saved as {file_path}")
    except IOError as e:
        print(f"Image saving error: {e}")

Key points:

If there is a problem during saving, such as a path error, IOError will prompt you.

3. Main program logic

This is the entry to the entire program.

if __name__ == "__main__":
    # Define the URL and save path of the image    url = "/photos/531294/?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2"
    local_file_path = "downloaded_image.jpg"

    # Loading pictures    image = load_image_from_url(url)

    if image:
        # Show pictures        ()

        # Save the picture        save_image(image, local_file_path)

Running results

The program will download and display the picture.

The image will be saved to the location you specified, such as downloaded_image.jpg in the current folder.

Summarize

This code shows how to complete a small project in Python. It is both simple and practical, and is a good example of how beginners learn programming.

This is the article about using Python to download and save network pictures. For more related Python download and save network pictures, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!