Compresseur d'image
Réduisez la taille des fichiers image avec un curseur de qualité — comparez avant et après.
Questions Fréquentes
Implémentation du Code
# Compress images with Pillow
# pip install Pillow
from PIL import Image
import os
def compress_image(input_path: str, output_path: str, quality: int = 80,
max_width: int = None, format: str = None) -> dict:
"""
Compress an image file.
quality: 1-95 for JPEG/WebP (80-85 is a good balance)
max_width: resize to this width while maintaining aspect ratio (optional)
format: "JPEG", "WEBP", "PNG" — defaults to same as input
"""
img = Image.open(input_path)
original_size = os.path.getsize(input_path)
# Convert RGBA to RGB for JPEG output
output_format = format or img.format or "JPEG"
if output_format.upper() in ("JPEG", "JPG") and img.mode in ("RGBA", "P"):
img = img.convert("RGB")
# Optional resize
if max_width and img.width > max_width:
ratio = max_width / img.width
new_size = (max_width, int(img.height * ratio))
img = img.resize(new_size, Image.LANCZOS)
save_kwargs = {}
if output_format.upper() in ("JPEG", "JPG"):
save_kwargs = {"quality": quality, "optimize": True, "progressive": True}
elif output_format.upper() == "WEBP":
save_kwargs = {"quality": quality, "method": 6}
elif output_format.upper() == "PNG":
save_kwargs = {"optimize": True, "compress_level": 9}
img.save(output_path, format=output_format.upper(), **save_kwargs)
new_size = os.path.getsize(output_path)
reduction = (1 - new_size / original_size) * 100
print(f"Original: {original_size/1024:.1f} KB")
print(f"Compressed: {new_size/1024:.1f} KB")
print(f"Reduction: {reduction:.1f}%")
return {"original_kb": original_size/1024, "compressed_kb": new_size/1024, "reduction_pct": reduction}
# Batch compress all images in a folder
import glob
def batch_compress(folder: str, quality: int = 80):
for path in glob.glob(f"{folder}/*.jpg") + glob.glob(f"{folder}/*.jpeg"):
name = os.path.splitext(path)[0]
out = f"{name}_compressed.jpg"
compress_image(path, out, quality=quality)
print(f"Processed: {os.path.basename(path)}")
# Usage
compress_image("photo.jpg", "photo_compressed.jpg", quality=80)
compress_image("image.png", "image.webp", format="WEBP", quality=80)
batch_compress("./images", quality=75)Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.