Last modified: Apr 12, 2025 By Alexander Williams

Python Download Images from URLs Guide

Downloading images from URLs is a common task in Python. This guide shows you how to do it easily.

Why Download Images with Python?

Python makes it simple to fetch images from the web. You can automate downloads for projects.

Use cases include web scraping, data collection, and machine learning. It saves time compared to manual downloads.

Required Libraries

You'll need two main libraries: requests and Pillow (PIL).

Install them using pip:


pip install requests pillow

Basic Image Download

Here's how to download an image using the requests library:


import requests

url = "https://example.com/image.jpg"
response = requests.get(url)

if response.status_code == 200:
    with open("image.jpg", "wb") as f:
        f.write(response.content)
    print("Image downloaded successfully")
else:
    print("Failed to download image")

This code fetches the image and saves it locally. The wb mode writes binary data.

Handling Different Image Formats

You can download various image formats like PNG, JPEG, or GIF. The process remains the same.

For more advanced image handling, see our Python PIL Image Handling Guide.

Using PIL to Verify Images

After downloading, you can verify the image using PIL:


from PIL import Image
import io

img_data = response.content
img = Image.open(io.BytesIO(img_data))
img.verify()  # Verifies image integrity
print("Image is valid")

Download Multiple Images

To download multiple images, loop through a list of URLs:


urls = [
    "https://example.com/image1.jpg",
    "https://example.com/image2.png"
]

for i, url in enumerate(urls):
    response = requests.get(url)
    if response.status_code == 200:
        with open(f"image_{i}.jpg", "wb") as f:
            f.write(response.content)

This saves each image with a numbered filename. For resizing after download, check our Python Resizing Images Guide.

Error Handling

Always include error handling for robust code:


try:
    response = requests.get(url, timeout=10)
    response.raise_for_status()
except requests.exceptions.RequestException as e:
    print(f"Error downloading image: {e}")

Saving Image Metadata

Some images contain metadata. Learn how to preserve it in our Python Save Images with Metadata Guide.

Conclusion

Downloading images in Python is straightforward with requests and PIL. This guide covered the basics.

You can now fetch single or multiple images from URLs. Remember to handle errors and verify downloads.

For more advanced image processing, explore our other Python image guides.