File size: 2,528 Bytes
c9c230c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

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)