NTO-TCP-HF / src /components /auto_crop.py
ishworrsubedii's picture
add: image preprocessing
1fb00de
"""
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)}")