File size: 1,711 Bytes
1fb00de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
project @ NTO-TCP-HF
created @ 2024-10-28
author  @ github.com/ishworrsubedii
"""
from io import BytesIO

from PIL import Image


def crop_transparent_image(image_data: bytes) -> tuple[bytes, dict]:
    try:
        image = Image.open(BytesIO(image_data))

        if image.format != 'PNG':
            raise ValueError("Only PNG images are supported")

        width = image.size[0]
        height = image.size[1]
        pixels = image.load()

        top = height
        bottom = 0
        left = width
        right = 0

        # Find boundaries of non-transparent pixels
        for y in range(height):
            for x in range(width):
                pixel = pixels[x, y]
                if isinstance(pixel, tuple) and len(pixel) == 4:
                    if pixel[3] != 0:
                        left = min(left, x)
                        top = min(top, y)
                        right = max(right, x)
                        bottom = max(bottom, y)

        left = max(0, left)
        top = max(0, top)
        right = min(width, right + 1)
        bottom = min(height, bottom + 1)

        if left >= right or top >= bottom:
            left, top, right, bottom = 0, 0, width, height

        # Crop image
        cropped_image = image.crop((left, top, right, bottom))

        output_buffer = BytesIO()
        cropped_image.save(output_buffer, format='PNG')
        output_buffer.seek(0)

        metadata = {
            "original_size": f"{width}x{height}",
            "cropped_size": f"{cropped_image.width}x{cropped_image.height}"
        }

        return output_buffer.getvalue(), metadata

    except Exception as e:
        raise ValueError(f"Error processing image: {str(e)}")