File size: 2,994 Bytes
eba303d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import base64
import time
from io import BytesIO

from PIL import Image
from loguru import logger


def crop_image(img: Image, new_size: tuple[int, int]) -> Image:
    """
    Crop an image to the specified size, maintaining the aspect ratio.
    :param img: The image to crop.
    :param new_size: The target size of the cropped image.
    :return: The cropped image.
    """
    width, height = img.size

    target_width, target_height = new_size

    aspect_ratio = width / height
    target_aspect_ratio = target_width / target_height

    if aspect_ratio > target_aspect_ratio:
        new_height = target_height
        new_width = int(aspect_ratio * new_height)
    else:
        new_width = target_width
        new_height = int(new_width / aspect_ratio)

    img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)

    left = (new_width - target_width) / 2
    top = (new_height - target_height) / 2
    right = (new_width + target_width) / 2
    bottom = (new_height + target_height) / 2

    return img.crop((left, top, right, bottom))


def encode_image_to_webp_base64(filepath):
    """
    Encodes an image file to WEBP and then to a Base64 string.

    :param filepath: Path to the image file
    :return: Base64 encoded string of the WEBP image
    :raises ValueError: If filepath is None or other issues occur during encoding
    """
    start_time = time.time()
    if filepath is None:
        raise ValueError("File path is None.")

    try:
        pil_image = Image.open(filepath)

        if pil_image.mode == 'RGBA':
            pil_image = pil_image.convert('RGB')

        buffered = BytesIO()
        pil_image.save(buffered, format="WEBP")

        base64_image = base64.b64encode(buffered.getvalue()).decode('utf-8')
        return base64_image

    except Exception as e:
        raise ValueError(f"Failed to encode image to WEBP base64: {str(e)}")
    finally:
        end_time = time.time()
        elapsed_time = end_time - start_time
        logger.info(f"Encoding image to WebP and Base64 spent {elapsed_time:.2f} seconds to process.")


def encode_webp_to_base64(image_file):
    """
    Encodes a WEBP image file (from HTTP upload) directly to a Base64 string.

    :param image_file: InMemoryUploadedFile object containing the WEBP image
    :return: Base64 encoded string of the WEBP image
    :raises ValueError: If image_file is None or other issues occur during encoding
    """
    start_time = time.time()
    if image_file is None:
        raise ValueError("Image file is None.")

    try:
        # Ensure that the file is read as binary data
        base64_image = base64.b64encode(image_file.read()).decode('utf-8')
        return base64_image

    except Exception as e:
        raise ValueError(f"Failed to encode WEBP image to Base64: {str(e)}")
    finally:
        end_time = time.time()
        elapsed_time = end_time - start_time
        logger.info(f"Encoding image to Base64 spent {elapsed_time:.2f} seconds to process.")