1 | import base64 |
2 | from PIL import Image, UnidentifiedImageError |
3 | import io |
4 |
|
5 | def main(image_base64: str): |
6 | try: |
7 | # Decode the base64 encoded image |
8 | image_data = base64.b64decode(image_base64) |
9 |
|
10 | # Convert the binary data to an image |
11 | image = Image.open(io.BytesIO(image_data)) |
12 |
|
13 | # Compress the image |
14 | |
15 | # The "optimize" flag can be used to reduce the file size without losing any quality. |
16 | with io.BytesIO() as output: |
17 | image.save( |
18 | output, format="PNG", optimize=True |
19 | ) # Using optimize flag for PNG compression |
20 | compressed_data = output.getvalue() |
21 |
|
22 | # Encode the compressed image to base64 |
23 | compressed_base64 = base64.b64encode(compressed_data).decode("utf-8") |
24 |
|
25 | # Return the base64 encoded compressed image |
26 | return { |
27 | "file": { |
28 | "content": compressed_base64, |
29 | "filename": "compressed_image.png", |
30 | } |
31 | } |
32 |
|
33 | except UnidentifiedImageError: |
34 | # Handle the case where the image cannot be identified |
35 | return "Error: The provided data does not represent a valid image." |
36 |
|