recipes: replace placeholder images with OKLAB dominant color backgrounds

Instead of generating/serving 20px placeholder images with blur CSS, extract
a perceptually accurate dominant color (Gaussian-weighted OKLAB average) and
use it as a solid background-color while the full image loads. Removes
placeholder image generation, blur CSS/JS, and placeholder directory references
across upload flows, API routes, service worker, and all card/hero components.
Adds admin bulk tool to backfill colors for existing recipes.
This commit is contained in:
2026-02-17 18:12:36 +01:00
parent 0ea09e424e
commit 53da9ad26d
21 changed files with 592 additions and 108 deletions

View File

@@ -37,6 +37,9 @@
const heroImg = $derived(
heroRecipe ? heroRecipe.images[0].mediapath : ''
);
const heroColor = $derived(
heroRecipe ? (heroRecipe.images[0].color || '') : ''
);
// Category chip state: 'all', 'season', or a category name
let activeChip = $state('all');
@@ -343,7 +346,7 @@
{#if heroRecipe}
<section class="hero-section">
<figure class="hero">
<figure class="hero" style:background-color={heroColor}>
<img
class="hero-img"
src="https://bocken.org/static/rezepte/full/{heroImg}"

View File

@@ -40,7 +40,7 @@
`${data.germanShortName || data.short_name}.webp`
);
const hero_img_src = $derived("https://bocken.org/static/rezepte/full/" + img_filename);
const placeholder_src = $derived("https://bocken.org/static/rezepte/placeholder/" + img_filename);
const img_color = $derived(data.images?.[0]?.color || '');
// Get alt text from images array
const img_alt = $derived(data.images?.[0]?.alt || '');
@@ -299,7 +299,7 @@ h2{
<link rel="alternate" hreflang="x-default" href="https://bocken.org/rezepte/{data.germanShortName}" />
</svelte:head>
<TitleImgParallax src={hero_img_src} {placeholder_src} alt={img_alt}>
<TitleImgParallax src={hero_img_src} color={img_color} alt={img_alt}>
<div class=title>
{#if data.category}
<a class="category g-pill g-btn-dark" href='/{data.recipeLang}/category/{data.category}'>{data.category}</a>

View File

@@ -69,7 +69,7 @@ export const actions = {
try {
console.log('[RecipeAdd] Starting image processing...');
// Process and save the image
const { filename } = await processAndSaveRecipeImage(
const { filename, color } = await processAndSaveRecipeImage(
recipeImage,
recipeData.short_name,
IMAGE_DIR
@@ -79,7 +79,8 @@ export const actions = {
recipeData.images = [{
mediapath: filename,
alt: '',
caption: ''
caption: '',
color
}];
} catch (imageError: any) {
console.error('[RecipeAdd] Image processing error:', imageError);

View File

@@ -0,0 +1,19 @@
import type { PageServerLoad } from './$types';
import { redirect, error } from '@sveltejs/kit';
export const load: PageServerLoad = async ({ locals, url }) => {
const session = await locals.auth();
if (!session?.user?.nickname) {
const callbackUrl = encodeURIComponent(url.pathname);
throw redirect(302, `/login?callbackUrl=${callbackUrl}`);
}
if (!session.user.groups?.includes('rezepte_users')) {
throw error(403, 'Zugriff verweigert. Du hast keine Berechtigung für diesen Bereich.');
}
return {
user: session.user
};
};

View File

@@ -0,0 +1,243 @@
<script>
import { onMount } from 'svelte';
let stats = $state({
totalWithImages: 0,
missingColor: 0,
withColor: 0,
});
let processing = $state(false);
let filter = $state('missing');
let limit = $state(50);
let results = $state([]);
let errorMsg = $state('');
onMount(async () => {
await fetchStats();
});
async function fetchStats() {
try {
const response = await fetch('/api/recalculate-image-colors');
if (response.ok) {
stats = await response.json();
}
} catch (err) {
console.error('Failed to fetch stats:', err);
}
}
async function processBatch() {
processing = true;
errorMsg = '';
results = [];
try {
const response = await fetch('/api/recalculate-image-colors', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ filter, limit }),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'Failed to process batch');
}
results = data.results || [];
await fetchStats();
} catch (err) {
errorMsg = err instanceof Error ? err.message : 'An error occurred';
} finally {
processing = false;
}
}
</script>
<style>
.container {
max-width: 1200px;
margin: 2rem auto;
padding: 2rem;
}
h1 {
color: var(--nord0);
margin-bottom: 2rem;
}
@media (prefers-color-scheme: dark) {
h1 { color: white; }
}
.stats {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1rem;
margin-bottom: 2rem;
}
.stat-card {
padding: 1.5rem;
background-color: var(--nord6);
border-radius: 0.5rem;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
@media (prefers-color-scheme: dark) {
.stat-card { background-color: var(--nord0); }
}
.stat-label {
font-size: 0.9rem;
color: var(--nord3);
margin-bottom: 0.5rem;
}
.stat-value {
font-size: 2rem;
font-weight: bold;
color: var(--nord10);
}
.controls {
background-color: var(--nord6);
padding: 1.5rem;
border-radius: 0.5rem;
margin-bottom: 2rem;
}
@media (prefers-color-scheme: dark) {
.controls { background-color: var(--nord1); }
}
.control-group {
margin-bottom: 1rem;
}
label {
display: block;
margin-bottom: 0.5rem;
font-weight: bold;
}
select, input {
padding: 0.5rem;
border-radius: 0.25rem;
border: 1px solid var(--nord4);
background-color: white;
}
@media (prefers-color-scheme: dark) {
select, input {
background-color: var(--nord0);
color: white;
border-color: var(--nord2);
}
}
button {
padding: 0.75rem 1.5rem;
background-color: var(--nord8);
color: white;
border: none;
border-radius: 0.25rem;
cursor: pointer;
font-size: 1rem;
font-weight: bold;
transition: background-color 0.2s;
}
button:hover { background-color: var(--nord7); }
button:disabled {
background-color: var(--nord3);
cursor: not-allowed;
}
.results {
margin-top: 2rem;
}
.result-item {
padding: 1rem;
background-color: var(--nord6);
border-radius: 0.25rem;
margin-bottom: 0.5rem;
display: flex;
align-items: center;
gap: 1rem;
}
@media (prefers-color-scheme: dark) {
.result-item { background-color: var(--nord1); }
}
.color-swatch {
width: 2.5rem;
height: 2.5rem;
border-radius: 0.25rem;
border: 1px solid var(--nord4);
flex-shrink: 0;
}
.result-info {
flex: 1;
}
.result-error {
color: var(--nord11);
font-size: 0.85rem;
}
.error {
padding: 1rem;
background-color: var(--nord11);
color: white;
border-radius: 0.25rem;
margin-bottom: 1rem;
}
</style>
<div class="container">
<h1>Image Dominant Colors</h1>
<div class="stats">
<div class="stat-card">
<div class="stat-label">Recipes with Images</div>
<div class="stat-value">{stats.totalWithImages}</div>
</div>
<div class="stat-card">
<div class="stat-label">Missing Color</div>
<div class="stat-value">{stats.missingColor}</div>
</div>
<div class="stat-card">
<div class="stat-label">With Color</div>
<div class="stat-value">{stats.withColor}</div>
</div>
</div>
<div class="controls">
<div class="control-group">
<label for="filter">Filter:</label>
<select id="filter" bind:value={filter}>
<option value="missing">Only Missing Colors</option>
<option value="all">All Recipes (Recalculate)</option>
</select>
</div>
<div class="control-group">
<label for="limit">Batch Size:</label>
<input id="limit" type="number" bind:value={limit} min="1" max="500" />
</div>
<button onclick={processBatch} disabled={processing}>
{processing ? 'Processing...' : 'Extract Colors'}
</button>
</div>
{#if errorMsg}
<div class="error">{errorMsg}</div>
{/if}
{#if results.length > 0}
<div class="results">
<h2>Results ({results.filter(r => r.status === 'ok').length} ok, {results.filter(r => r.status === 'error').length} failed)</h2>
{#each results as result}
<div class="result-item">
{#if result.status === 'ok'}
<div class="color-swatch" style="background-color: {result.color}"></div>
{/if}
<div class="result-info">
<strong>{result.name}</strong> ({result.shortName})
{#if result.status === 'ok'}
<code>{result.color}</code>
{/if}
{#if result.status === 'error'}
<div class="result-error">{result.error}</div>
{/if}
</div>
</div>
{/each}
</div>
{/if}
</div>

View File

@@ -25,6 +25,14 @@
: 'Alternativtext für Rezeptbilder mit KI generieren',
href: `/${data.recipeLang}/admin/alt-text-generator`,
icon: '🖼️'
},
{
title: isEnglish ? 'Image Colors' : 'Bildfarben',
description: isEnglish
? 'Extract dominant colors from recipe images for loading placeholders'
: 'Dominante Farben aus Rezeptbildern für Ladeplatzhalter extrahieren',
href: `/${data.recipeLang}/admin/image-colors`,
icon: '🎨'
}
];
</script>

View File

@@ -22,7 +22,7 @@ import {
async function deleteRecipeImage(filename: string): Promise<void> {
if (!filename) return;
const imageDirectories = ['full', 'thumb', 'placeholder'];
const imageDirectories = ['full', 'thumb'];
// Extract basename to handle both hashed and unhashed versions
const basename = filename
@@ -119,7 +119,7 @@ export const actions = {
if (recipeImage && recipeImage.size > 0) {
try {
// Process and save the new image
const { filename } = await processAndSaveRecipeImage(
const { filename, color } = await processAndSaveRecipeImage(
recipeImage,
recipeData.short_name,
IMAGE_DIR
@@ -133,7 +133,8 @@ export const actions = {
recipeData.images = [{
mediapath: filename,
alt: existingImagePath ? (recipeData.images?.[0]?.alt || '') : '',
caption: existingImagePath ? (recipeData.images?.[0]?.caption || '') : ''
caption: existingImagePath ? (recipeData.images?.[0]?.caption || '') : '',
color
}];
} catch (imageError: any) {
console.error('Image processing error:', imageError);
@@ -161,7 +162,7 @@ export const actions = {
// Handle short_name change (rename images)
if (originalShortName !== recipeData.short_name) {
const imageDirectories = ['full', 'thumb', 'placeholder'];
const imageDirectories = ['full', 'thumb'];
for (const dir of imageDirectories) {
const oldPath = join(IMAGE_DIR, 'rezepte', dir, `${originalShortName}.webp`);