Spaces:
Paused
Paused
Upload helpers/images.py with huggingface_hub
Browse files- helpers/images.py +35 -3
helpers/images.py
CHANGED
|
@@ -1,3 +1,35 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from PIL import Image
|
| 2 |
+
import io
|
| 3 |
+
import math
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def compress_image(image_data: bytes, *, max_pixels: int = 256_000, quality: int = 50) -> bytes:
|
| 7 |
+
"""Compress an image by scaling it down and converting to JPEG with quality settings.
|
| 8 |
+
|
| 9 |
+
Args:
|
| 10 |
+
image_data: Raw image bytes
|
| 11 |
+
max_pixels: Maximum number of pixels in the output image (width * height)
|
| 12 |
+
quality: JPEG quality setting (1-100)
|
| 13 |
+
|
| 14 |
+
Returns:
|
| 15 |
+
Compressed image as bytes
|
| 16 |
+
"""
|
| 17 |
+
# load image from bytes
|
| 18 |
+
img = Image.open(io.BytesIO(image_data))
|
| 19 |
+
|
| 20 |
+
# calculate scaling factor to get to max_pixels
|
| 21 |
+
current_pixels = img.width * img.height
|
| 22 |
+
if current_pixels > max_pixels:
|
| 23 |
+
scale = math.sqrt(max_pixels / current_pixels)
|
| 24 |
+
new_width = int(img.width * scale)
|
| 25 |
+
new_height = int(img.height * scale)
|
| 26 |
+
img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
| 27 |
+
|
| 28 |
+
# convert to RGB if needed (for JPEG)
|
| 29 |
+
if img.mode in ('RGBA', 'P'):
|
| 30 |
+
img = img.convert('RGB')
|
| 31 |
+
|
| 32 |
+
# save as JPEG with compression
|
| 33 |
+
output = io.BytesIO()
|
| 34 |
+
img.save(output, format='JPEG', quality=quality, optimize=True)
|
| 35 |
+
return output.getvalue()
|