File size: 1,675 Bytes
7baafc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import time
from functools import wraps
import base64
from io import BytesIO


def timing_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        execution_time = end_time - start_time
        print(f"Function {func.__name__} took {execution_time:.4f} seconds to execute.")
        return result
    return wrapper

def pil_image_to_base64_url(image, format='JPEG'):
    """
    Convert a PIL image to a Base64-encoded URL.
    
    :param image: PIL image object
    :param format: Image format (default is JPEG)
    :return: Base64 URL string
    """
    # Create a BytesIO object to hold the image in memory
    buffered = BytesIO()
    
    # Save the image in the provided format (e.g., JPEG or PNG)
    image.save(buffered, format=format)
    
    # Get the base64 encoded string
    img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
    
    # Create the Base64 URL string
    base64_url = f"data:image/{format.lower()};base64,{img_str}"
    
    return base64_url

def pil_image_to_data_url(pil_image):
    # Convert the image to RGB mode if it's not already
    if pil_image.mode != 'RGB':
        pil_image = pil_image.convert('RGB')
    
    # Create a BytesIO object to store the image data
    buffered = BytesIO()
    
    # Save the image as JPEG to the BytesIO object
    pil_image.save(buffered, format="JPEG")
    
    # Encode the image data as base64
    img_str = base64.b64encode(buffered.getvalue()).decode()
    
    # Create the data URL
    data_url = f"data:image/jpeg;base64,{img_str}"
    
    return data_url