|
| 1 | +from PIL import Image |
| 2 | + |
| 3 | +def compress_image(input_path, output_path, quality=20, max_width=None, max_height=None): |
| 4 | + # Open an image file |
| 5 | + with Image.open(input_path) as img: |
| 6 | + # Convert image to RGB mode if it's in P mode |
| 7 | + if img.mode == 'P': |
| 8 | + img = img.convert('RGB') |
| 9 | + |
| 10 | + # Resize image if max_width or max_height is provided |
| 11 | + if max_width or max_height: |
| 12 | + # Calculate aspect ratio |
| 13 | + aspect_ratio = img.width / img.height |
| 14 | + |
| 15 | + if max_width and max_height: |
| 16 | + # Determine the new size keeping the aspect ratio |
| 17 | + if img.width / max_width > img.height / max_height: |
| 18 | + new_width = max_width |
| 19 | + new_height = int(max_width / aspect_ratio) |
| 20 | + else: |
| 21 | + new_height = max_height |
| 22 | + new_width = int(max_height * aspect_ratio) |
| 23 | + elif max_width: |
| 24 | + new_width = max_width |
| 25 | + new_height = int(max_width / aspect_ratio) |
| 26 | + elif max_height: |
| 27 | + new_height = max_height |
| 28 | + new_width = int(max_height * aspect_ratio) |
| 29 | + |
| 30 | + img = img.resize((new_width, new_height), Image.Resampling.LANCZOS) |
| 31 | + |
| 32 | + # Save it with a new name and quality |
| 33 | + img.save(output_path, "JPEG", quality=quality) |
| 34 | + |
| 35 | +# Example usage |
| 36 | +input_image_path = "back.png" # This can be a PNG, GIF, etc. |
| 37 | +output_image_path = "compressed_image.jpg" |
| 38 | +compress_image(input_image_path, output_image_path, quality=30, max_width=3467) |
0 commit comments