Skip to content

Commit 6f4c290

Browse files
authored
compress_img.py
1 parent 782a1fb commit 6f4c290

File tree

1 file changed

+2
-9
lines changed

1 file changed

+2
-9
lines changed

compresse_img/compress_img.py

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,14 @@
11
from PIL import Image
22

33
def compress_image(input_path, output_path, quality=20, max_width=None, max_height=None):
4-
# Open an image file
54
with Image.open(input_path) as img:
6-
# Convert image to RGB mode if it's in P mode
75
if img.mode == 'P':
86
img = img.convert('RGB')
97

10-
# Resize image if max_width or max_height is provided
118
if max_width or max_height:
12-
# Calculate aspect ratio
139
aspect_ratio = img.width / img.height
1410

1511
if max_width and max_height:
16-
# Determine the new size keeping the aspect ratio
1712
if img.width / max_width > img.height / max_height:
1813
new_width = max_width
1914
new_height = int(max_width / aspect_ratio)
@@ -29,10 +24,8 @@ def compress_image(input_path, output_path, quality=20, max_width=None, max_heig
2924

3025
img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
3126

32-
# Save it with a new name and quality
3327
img.save(output_path, "JPEG", quality=quality)
3428

35-
# Example usage
36-
input_image_path = "back.png" # This can be a PNG, GIF, etc.
37-
output_image_path = "compressed_image.jpg"
29+
input_image_path = "1.png"
30+
output_image_path = "2.jpg"
3831
compress_image(input_image_path, output_image_path, quality=30, max_width=3467)

0 commit comments

Comments
 (0)