import os from PIL import Image def generate_thumbnails(): src_base = os.path.join("pfm-web-app", "public", "produk-pfm", "foto-kemasan-v2") dest_base = os.path.join("pfm-web-app", "public", "produk-pfm", "thumbs") if not os.path.exists(src_base): print(f"Source directory {src_base} does not exist.") return # Supported image extensions valid_exts = (".jpg", ".jpeg", ".png", ".webp", ".bmp") count = 0 # Walk through the source directory for root, dirs, files in os.walk(src_base): for file in files: if file.lower().endswith(valid_exts): src_path = os.path.join(root, file) # Get the relative path from the source base rel_path = os.path.relpath(src_path, src_base) dest_path = os.path.join(dest_base, rel_path) # Ensure destination directory exists dest_dir = os.path.dirname(dest_path) os.makedirs(dest_dir, exist_ok=True) try: with Image.open(src_path) as img: # Resize to maximum dimension of 120px while preserving aspect ratio img.thumbnail((120, 120)) # Save the thumbnail img.save(dest_path) print(f"Generated thumbnail: {dest_path}") count += 1 except Exception as e: print(f"Failed to generate thumbnail for {src_path}: {e}") print(f"Successfully generated {count} thumbnails.") if __name__ == "__main__": generate_thumbnails()