|
| 1 | +from PIL import Image |
| 2 | +import os |
| 3 | + |
| 4 | + |
| 5 | +def crop_to_ratio(img, target_ratio): |
| 6 | + """Crop image to target ratio (e.g., 16/9 or 1/1) without distortion.""" |
| 7 | + width, height = img.size |
| 8 | + current_ratio = width / height |
| 9 | + |
| 10 | + if current_ratio > target_ratio: |
| 11 | + # Crop width |
| 12 | + new_width = int(height * target_ratio) |
| 13 | + left = (width - new_width) // 2 |
| 14 | + return img.crop((left, 0, left + new_width, height)) |
| 15 | + else: |
| 16 | + # Crop height |
| 17 | + new_height = int(width / target_ratio) |
| 18 | + top = (height - new_height) // 2 |
| 19 | + return img.crop((0, top, width, top + new_height)) |
| 20 | + |
| 21 | +def process_image(file_path, ratio, max_size, format="webp"): |
| 22 | + """Process and overwrite the original image: crop, resize, convert format.""" |
| 23 | + try: |
| 24 | + with Image.open(file_path) as img: |
| 25 | + # Crop to target ratio |
| 26 | + if ratio: |
| 27 | + img = crop_to_ratio(img, ratio) |
| 28 | + |
| 29 | + # Resize to max dimensions |
| 30 | + if max_size: |
| 31 | + img.thumbnail(max_size) |
| 32 | + |
| 33 | + # convert to webp if no transparency |
| 34 | + if format.lower() == "webp" and img.mode != "RGBA": |
| 35 | + file_path = os.path.splitext(file_path)[0] + ".webp" |
| 36 | + img.save(file_path, "webp", optimize=True, quality=85) |
| 37 | + else: |
| 38 | + img.save(file_path, optimize=True) |
| 39 | + |
| 40 | + print(f"✅ Overwritten: {file_path}") |
| 41 | + except Exception as e: |
| 42 | + print(f"❌ Failed {file_path}: {str(e)}") |
| 43 | + |
| 44 | +def main(): |
| 45 | + folder = "assets/images" |
| 46 | + |
| 47 | + # Rules for image types |
| 48 | + rules = [ |
| 49 | + { |
| 50 | + "suffix": ["banner", "header"], |
| 51 | + "ratio": 16/9, |
| 52 | + "max_size": (1920, 1080), # Min size enforced via cropping |
| 53 | + "format": "webp" |
| 54 | + }, |
| 55 | + { |
| 56 | + "suffix": ["thumb", "profile"], |
| 57 | + "ratio": 1/1, |
| 58 | + "max_size": (800, 800), |
| 59 | + "format": "webp" |
| 60 | + } |
| 61 | + ] |
| 62 | + |
| 63 | + for filename in os.listdir(folder): |
| 64 | + if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.webp')): |
| 65 | + file_path = os.path.join(folder, filename) |
| 66 | + |
| 67 | + # Apply first rule |
| 68 | + matched_rule = None |
| 69 | + for rule in rules: |
| 70 | + if any(keyword in filename.lower() for keyword in rule["suffix"]): |
| 71 | + matched_rule = rule |
| 72 | + break |
| 73 | + |
| 74 | + # no cropping, resize to 800x600, convert to webp if no transparency |
| 75 | + if not matched_rule: |
| 76 | + with Image.open(file_path) as img: |
| 77 | + format = "webp" if img.mode != "RGBA" else "png" |
| 78 | + matched_rule = {"ratio": None, "max_size": (800, 600), "format": format} |
| 79 | + |
| 80 | + process_image(file_path, **matched_rule) |
| 81 | + |
| 82 | +if __name__ == "__main__": |
| 83 | + main() |
0 commit comments