Downloading an image from the internet can be done easily with Python. Instead of right-clicking and saving an image manually, you can automate the task with a simple Python script. This is especially useful for projects where you need to download multiple images or work with images in bulk.
Why Learn This?
Downloading images using Python saves time and effort. Whether you’re building a dataset, scraping images for a project, or automating tasks, this skill can be a handy tool in your programming toolkit.
Step-by-Step Guide
1.Install the Required Library You need the requests library to download the image. If you don’t have it, install it by running:
pip install requests
2.Import the Library Start your script by importing the requests library. This helps your code fetch the image from the internet.
import requests
3.Specify the Image URL Provide the direct URL of the image you want to download. Replace the example link with the actual image link.
import requests url = "https://example.com/image.jpg"
4.Download the Image Use requests.get() to fetch the image from the URL. This sends a request to the server and stores the image data.
import requests url = "https://example.com/image.jpg" response = requests.get(url)
5.Save the Image Locally If the request is successful, save the image to your computer. Open a file in binary write mode (wb) and write the image data into it.
import requests url = "https://example.com/image.jpg" response = requests.get(url) if response.status_code == 200: with open("downloaded_image.jpg", "wb") as file: file.write(response.content) print("Image downloaded successfully!") else: print(f"Failed to download image. Error code: {response.status_code}")