perf: optimize kniepunkt images to webp, add lazy loading and thumbnails
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
import os
|
||||
from PIL import Image
|
||||
from pathlib import Path
|
||||
|
||||
BASE_DIR = Path("/home/andre/coden/Orchestrator/privat/CV/andreknie.de")
|
||||
IMG_DIR = BASE_DIR / "public/images/kniepunkt"
|
||||
MD_DIR = BASE_DIR / "content/kniepunkt"
|
||||
|
||||
def optimize_images():
|
||||
# Find all PNG files
|
||||
png_files = list(IMG_DIR.glob("*.png"))
|
||||
print(f"Found {len(png_files)} PNG files to process.")
|
||||
|
||||
for png in png_files:
|
||||
try:
|
||||
with Image.open(png) as img:
|
||||
# Convert to RGB if necessary
|
||||
if img.mode in ("RGBA", "P"):
|
||||
img = img.convert("RGBA")
|
||||
|
||||
# Full size optimization (max width 1200)
|
||||
full_img = img.copy()
|
||||
if full_img.width > 1200:
|
||||
ratio = 1200 / full_img.width
|
||||
new_size = (1200, int(full_img.height * ratio))
|
||||
full_img = full_img.resize(new_size, Image.Resampling.LANCZOS)
|
||||
|
||||
webp_path = png.with_suffix(".webp")
|
||||
full_img.save(webp_path, "WEBP", quality=80)
|
||||
|
||||
# Thumbnail optimization (max width 600)
|
||||
thumb_img = img.copy()
|
||||
if thumb_img.width > 600:
|
||||
ratio = 600 / thumb_img.width
|
||||
new_size = (600, int(thumb_img.height * ratio))
|
||||
thumb_img = thumb_img.resize(new_size, Image.Resampling.LANCZOS)
|
||||
|
||||
thumb_path = webp_path.with_name(f"{webp_path.stem}-thumb.webp")
|
||||
thumb_img.save(thumb_path, "WEBP", quality=75)
|
||||
|
||||
# Remove original PNG to save space
|
||||
png.unlink()
|
||||
print(f"Processed and replaced: {png.name} -> {webp_path.name} & {thumb_path.name}")
|
||||
except Exception as e:
|
||||
print(f"Error processing {png}: {e}")
|
||||
|
||||
def update_markdown():
|
||||
md_files = list(MD_DIR.glob("*.md"))
|
||||
print(f"\nUpdating {len(md_files)} Markdown files...")
|
||||
|
||||
for md in md_files:
|
||||
content = md.read_text(encoding="utf-8")
|
||||
if ".png" in content:
|
||||
new_content = content.replace(".png", ".webp")
|
||||
md.write_text(new_content, encoding="utf-8")
|
||||
print(f"Updated references in {md.name}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
optimize_images()
|
||||
update_markdown()
|
||||
print("Done!")
|
||||
Reference in New Issue
Block a user