Spaces:
Running
on
Zero
Running
on
Zero
from PIL import Image | |
import requests | |
from io import BytesIO | |
import logging | |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') | |
def load_image_from_url(url): | |
"""Loads an image from a URL. | |
Args: | |
url (str): The URL of the image. | |
Returns: | |
PIL.Image.Image: The loaded image. | |
Raises: | |
Exception: If the image cannot be loaded from the URL. | |
""" | |
try: | |
response = requests.get(url, stream=True) | |
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx) | |
image = Image.open(BytesIO(response.content)) | |
logging.info(f"Image loaded successfully from URL: {url}") | |
return image | |
except requests.exceptions.RequestException as e: | |
logging.error(f"Error loading image from URL: {url} - {e}") | |
raise Exception(f"Error loading image from URL: {url} - {e}") | |
except Exception as e: | |
logging.error(f"Error opening image from URL: {url} - {e}") | |
raise Exception(f"Error opening image from URL: {url} - {e}") | |
def load_image_from_file(file_path): | |
"""Loads an image from a file. | |
Args: | |
file_path (str): The path to the image file. | |
Returns: | |
PIL.Image.Image: The loaded image. | |
Raises: | |
Exception: If the image cannot be loaded from the file. | |
""" | |
try: | |
image = Image.open(file_path) | |
logging.info(f"Image loaded successfully from file: {file_path}") | |
return image | |
except FileNotFoundError: | |
logging.error(f"File not found: {file_path}") | |
raise Exception(f"File not found: {file_path}") | |
except Exception as e: | |
logging.error(f"Error loading image from file: {file_path} - {e}") | |
raise Exception(f"Error loading image from file: {file_path} - {e}") | |
if __name__ == '__main__': | |
# Example Usage | |
try: | |
image_url = "https://hips.hearstapps.com/hmg-prod/images/gettyimages-1229892983-square.jpg" | |
image_from_url = load_image_from_url(image_url) | |
print("Image loaded from URL successfully!") | |
# image_from_url.show() # Display the image (optional) | |
except Exception as e: | |
print(e) | |
try: | |
image_path = "butterfly.jpg" | |
image_from_file = load_image_from_file(image_path) | |
print("Image loaded from file successfully!") | |
# image_from_file.show() # Display the image (optional) | |
except Exception as e: | |
print(e) | |