In this article, we will see how to save an image locally from a URL using Python.

We will be using the requests library to download the image from a given URL. This library is widely used to make HTTP requests in Python.

To start, install the requests library using the PIP:

pip install requests

Once it is installed, we can use the requests library to download an image from the URL as shown in the following example:

import requests

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

with open("image.jpg", "wb") as f:
    f.write(response.content)

Explanation:

In the above example, we first import the requests library and then define the URL of the image that we want to download. We then use the requests.get() method to send an HTTP GET request to the URL and store the response in the response variable.

Next, we open a file using the open() method and pass the argument as "wb" to indicate that we want to write the image data in binary mode.

After opening the file in the write mode, we write the contents of the response to the file.

Finally, we close the file using the with statement to make sure that it is properly closed once the data has been written.

Categorized in:

Tagged in: