How to download a remote image and save it to your local machine in Python

Published on Aug. 22, 2023, 12:16 p.m.

To download a remote image and save it to your local machine in Python, you can use the requests library. Here’s an example code that demonstrates how to download an image from an URL and save it to a file:

import requests

url = 'https://www.example.com/image.jpg'
filename = 'image.jpg'

response = requests.get(url)

if response.status_code == 200:
    with open(filename, 'wb') as f:
        f.write(response.content)
    print('Image downloaded successfully')
else:
    print('Request failed')

In this code, we first send an HTTP GET request to the image URL using the requests library. We then use Python’s built-in open() function to open a file in binary write mode and write the response content to it using the write() method.

Note that there are many other libraries and frameworks that can be used to download and manipulate images in Python such as Pillow and OpenCV.

To download remote images using Pillow in Python

To download remote images using Pillow in Python, you can use the Image module of the Pillow library. Here’s an example code that demonstrates how to download a remote image using Pillow and save it to your local machine:

from PIL import Image
import requests

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

if response.status_code == 200:
    # Open the image from the response content
    image = Image.open(BytesIO(response.content))
    # Choose a new file name and format
    filename = 'new_image.png'
    # Save image file to local machine
    image.save(filename)
    print('Image downloaded and saved successfully')
else:
    print('Request failed')

In this code, we first send an HTTP GET request to the image URL using the requests library. We then use the Pillow Image.open() method to open the response content as an image object. We can then choose a new file name and format, and finally save the image file to the local machine using the Image.save() method.

Note that you need to import the BytesIO class from the io module to use the Image.open() method with the response content.

Tags:

related content