Download Image from URL Your Visual Resource Hub

Example Implementations: Download Image From Url

Download image from url

Diving into the practical realm of image downloading, we’ll explore hands-on examples using Python. From fetching a single image to handling multiple downloads and error situations, we’ll cover it all. We’ll also touch on image resizing and the power of asynchronous operations. Get ready to code!

Single Image Download

Downloading a single image from a URL is a fundamental task. The code below uses the `requests` library, a popular choice for HTTP requests in Python. This approach ensures reliable and efficient data retrieval.

“`python
import requests
from io import BytesIO
from PIL import Image

def download_image(url, filename):
try:
response = requests.get(url, stream=True)
response.raise_for_status() # Raise an exception for bad status codes
image = Image.open(BytesIO(response.content))
image.save(filename)
print(f”Image ‘filename’ downloaded successfully.”)
except requests.exceptions.RequestException as e:
print(f”Error downloading image: e”)
except Exception as e:
print(f”An unexpected error occurred: e”)

# Example usage
url = “https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/Example.jpg/1200px-Example.jpg”
filename = “example.jpg”
download_image(url, filename)
“`

This code snippet handles potential errors like network issues or invalid URLs gracefully. It utilizes `try…except` blocks to catch and report any problems. The `BytesIO` object is employed to temporarily store the image data, preventing memory issues with large files. Crucially, it checks the HTTP response status to ensure the download was successful.

Multiple Image Downloads

Downloading multiple images from different URLs requires a more structured approach. The code below efficiently handles this task.

“`python
import requests
from io import BytesIO
from PIL import Image
import os

def download_images(urls, output_dir):
os.makedirs(output_dir, exist_ok=True) # Create the output directory if it doesn’t exist

for i, url in enumerate(urls):
try:
response = requests.get(url, stream=True)
response.raise_for_status()
image = Image.open(BytesIO(response.content))
filename = os.path.join(output_dir, f”image_i+1.jpg”) # Add image number
image.save(filename)
print(f”Image ‘filename’ downloaded successfully.”)
except requests.exceptions.RequestException as e:
print(f”Error downloading image url: e”)
except Exception as e:
print(f”An unexpected error occurred while downloading image url: e”)

# Example usage (list of URLs)
urls = [
“https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/Example.jpg/1200px-Example.jpg”,
“https://www.easygifanimator.net/images/example-animated-gif.gif”,
“https://source.unsplash.com/random/1920×1080”
]
output_dir = “downloaded_images”
download_images(urls, output_dir)
“`

This improved version efficiently downloads multiple images. The `os.makedirs` function ensures the output directory is created, preventing errors if it doesn’t already exist.

Error Handling

Robust error handling is vital in any image downloading process. The code below demonstrates a comprehensive error-handling strategy.

“`python
# … (previous code) …
“`

This example illustrates comprehensive error handling using `try…except` blocks to catch various exceptions during the download process. This ensures the program doesn’t crash and provides informative error messages. Note the distinct handling of `requests` exceptions versus general exceptions.

Image Resizing

Resizing images after download is often necessary for optimal display or storage. The code below demonstrates this process using the `PIL` library.

“`python
from PIL import Image

def resize_image(input_path, output_path, width, height):
try:
img = Image.open(input_path)
img = img.resize((width, height))
img.save(output_path)
print(f”Image ‘input_path’ resized and saved to ‘output_path’.”)
except FileNotFoundError:
print(f”Error: Input image file ‘input_path’ not found.”)
except Exception as e:
print(f”An error occurred: e”)

# Example usage
resize_image(“example.jpg”, “resized_example.jpg”, 100, 100)
“`

Asynchronous Image Download, Download image from url

Asynchronous programming can significantly improve download performance, especially when dealing with multiple images. This example showcases the power of asynchronous operations using the `asyncio` library.

“`python
import asyncio
import aiohttp
from io import BytesIO
from PIL import Image

async def download_image_async(url, session, filename):
async with session.get(url, stream=True) as response:
response.raise_for_status()
image = Image.open(BytesIO(await response.read()))
image.save(filename)
print(f”Image ‘filename’ downloaded successfully.”)

async def main():
urls = [“https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/Example.jpg/1200px-Example.jpg”, “https://www.easygifanimator.net/images/example-animated-gif.gif”]
async with aiohttp.ClientSession() as session:
tasks = [download_image_async(url, session, f”image_i.jpg”) for i, url in enumerate(urls)]
await asyncio.gather(*tasks)

if __name__ == “__main__”:
asyncio.run(main())
“`

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
close
close