Spaces:
Sleeping
Sleeping
Create image_optimization_utils.py
Browse files- image_optimization_utils.py +42 -0
image_optimization_utils.py
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from PIL import Image
|
2 |
+
import io
|
3 |
+
|
4 |
+
def compress_image(image, quality=85):
|
5 |
+
"""
|
6 |
+
Komprimiert ein Bild mit angegebener Qualität
|
7 |
+
|
8 |
+
:param image: PIL Image Objekt
|
9 |
+
:param quality: Kompressionsqualität (1-100)
|
10 |
+
:return: Komprimiertes PIL Image
|
11 |
+
"""
|
12 |
+
img_byte_arr = io.BytesIO()
|
13 |
+
image.save(img_byte_arr, format='JPEG', quality=quality)
|
14 |
+
img_byte_arr.seek(0)
|
15 |
+
return Image.open(img_byte_arr)
|
16 |
+
|
17 |
+
def convert_image_format(image, target_format='webp', quality=85):
|
18 |
+
"""
|
19 |
+
Konvertiert Bild in Zielformat
|
20 |
+
|
21 |
+
:param image: PIL Image Objekt
|
22 |
+
:param target_format: Zielformat (jpg, png, webp)
|
23 |
+
:param quality: Kompressionsqualität
|
24 |
+
:return: Konvertiertes PIL Image
|
25 |
+
"""
|
26 |
+
img_byte_arr = io.BytesIO()
|
27 |
+
image.save(img_byte_arr, format=target_format.upper(), quality=quality)
|
28 |
+
img_byte_arr.seek(0)
|
29 |
+
return Image.open(img_byte_arr)
|
30 |
+
|
31 |
+
def resize_image(image, max_width=None, max_height=None):
|
32 |
+
"""
|
33 |
+
Ändert Bildgröße unter Beibehaltung des Seitenverhältnisses
|
34 |
+
|
35 |
+
:param image: PIL Image Objekt
|
36 |
+
:param max_width: Maximale Breite
|
37 |
+
:param max_height: Maximale Höhe
|
38 |
+
:return: Größenverändertes PIL Image
|
39 |
+
"""
|
40 |
+
if max_width and max_height:
|
41 |
+
image.thumbnail((max_width, max_height))
|
42 |
+
return image
|