diff --git a/src/lib/components/recipes/Card.svelte b/src/lib/components/recipes/Card.svelte
index 2cb9654..dc3bc40 100644
--- a/src/lib/components/recipes/Card.svelte
+++ b/src/lib/components/recipes/Card.svelte
@@ -36,6 +36,8 @@ const img_name = $derived(
const img_alt = $derived(
recipe.images?.[0]?.alt || recipe.name
);
+
+const img_color = $derived(recipe.images?.[0]?.color || '');
+
+
+
Image Dominant Colors
+
+
+
+
Recipes with Images
+
{stats.totalWithImages}
+
+
+
Missing Color
+
{stats.missingColor}
+
+
+
With Color
+
{stats.withColor}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {#if errorMsg}
+
{errorMsg}
+ {/if}
+
+ {#if results.length > 0}
+
+
Results ({results.filter(r => r.status === 'ok').length} ok, {results.filter(r => r.status === 'error').length} failed)
+ {#each results as result}
+
+ {#if result.status === 'ok'}
+
+ {/if}
+
+
{result.name} ({result.shortName})
+ {#if result.status === 'ok'}
+
{result.color}
+ {/if}
+ {#if result.status === 'error'}
+
{result.error}
+ {/if}
+
+
+ {/each}
+
+ {/if}
+
diff --git a/src/routes/[recipeLang=recipeLang]/administration/+page.svelte b/src/routes/[recipeLang=recipeLang]/administration/+page.svelte
index de0702d..cb085d1 100644
--- a/src/routes/[recipeLang=recipeLang]/administration/+page.svelte
+++ b/src/routes/[recipeLang=recipeLang]/administration/+page.svelte
@@ -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: '🎨'
}
];
diff --git a/src/routes/[recipeLang=recipeLang]/edit/[name]/+page.server.ts b/src/routes/[recipeLang=recipeLang]/edit/[name]/+page.server.ts
index 357a79f..a7dd37c 100644
--- a/src/routes/[recipeLang=recipeLang]/edit/[name]/+page.server.ts
+++ b/src/routes/[recipeLang=recipeLang]/edit/[name]/+page.server.ts
@@ -22,7 +22,7 @@ import {
async function deleteRecipeImage(filename: string): Promise {
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`);
diff --git a/src/routes/api/[recipeLang=recipeLang]/edit/+server.ts b/src/routes/api/[recipeLang=recipeLang]/edit/+server.ts
index df976d2..b5f7198 100644
--- a/src/routes/api/[recipeLang=recipeLang]/edit/+server.ts
+++ b/src/routes/api/[recipeLang=recipeLang]/edit/+server.ts
@@ -26,7 +26,7 @@ export const POST: RequestHandler = async ({request, locals}) => {
if (oldShortName !== newShortName) {
// Rename image files in all three directories
- const imageDirectories = ['full', 'thumb', 'placeholder'];
+ const imageDirectories = ['full', 'thumb'];
const staticPath = join(process.cwd(), 'static', 'rezepte');
for (const dir of imageDirectories) {
diff --git a/src/routes/api/[recipeLang=recipeLang]/img/add/+server.ts b/src/routes/api/[recipeLang=recipeLang]/img/add/+server.ts
index 64e5602..d7514f5 100644
--- a/src/routes/api/[recipeLang=recipeLang]/img/add/+server.ts
+++ b/src/routes/api/[recipeLang=recipeLang]/img/add/+server.ts
@@ -5,6 +5,7 @@ import { IMAGE_DIR } from '$env/static/private';
import sharp from 'sharp';
import { generateImageHashFromBuffer, getHashedFilename } from '$utils/imageHash';
import { validateImageFile } from '$utils/imageValidation';
+import { extractDominantColor } from '$utils/imageProcessing';
/**
* Secure image upload endpoint for recipe images
@@ -13,7 +14,7 @@ import { validateImageFile } from '$utils/imageValidation';
* - Requires authentication
* - 5-layer validation (size, magic bytes, MIME, extension, Sharp)
* - Uses FormData instead of base64 JSON (more efficient, more secure)
- * - Generates full/thumb/placeholder versions
+ * - Generates full/thumb versions + dominant color extraction
* - Content hash for cache busting
*
* @route POST /api/rezepte/img/add
@@ -109,31 +110,20 @@ export const POST = (async ({ request, locals }) => {
await sharp(thumbBuffer).toFile(thumbHashedPath);
await sharp(thumbBuffer).toFile(thumbUnhashedPath);
- console.log('[API:ImgAdd] Thumbnail images saved ✓');
+ console.log('[API:ImgAdd] Thumbnail images saved');
- // Save placeholder (20px width) - both hashed and unhashed versions
- console.log('[API:ImgAdd] Processing placeholder...');
- const placeholderBuffer = await sharp(buffer)
- .resize({ width: 20 })
- .toFormat('webp')
- .webp({ quality: 60 })
- .toBuffer();
- console.log('[API:ImgAdd] Placeholder buffer created, size:', placeholderBuffer.length, 'bytes');
+ // Extract dominant color
+ console.log('[API:ImgAdd] Extracting dominant color...');
+ const color = await extractDominantColor(buffer);
+ console.log('[API:ImgAdd] Dominant color:', color);
- const placeholderHashedPath = path.join(IMAGE_DIR, 'rezepte', 'placeholder', hashedFilename);
- const placeholderUnhashedPath = path.join(IMAGE_DIR, 'rezepte', 'placeholder', unhashedFilename);
- console.log('[API:ImgAdd] Saving placeholder to:', { placeholderHashedPath, placeholderUnhashedPath });
-
- await sharp(placeholderBuffer).toFile(placeholderHashedPath);
- await sharp(placeholderBuffer).toFile(placeholderUnhashedPath);
- console.log('[API:ImgAdd] Placeholder images saved ✓');
-
- console.log('[API:ImgAdd] Upload completed successfully ✓');
+ console.log('[API:ImgAdd] Upload completed successfully');
return json({
success: true,
msg: 'Image uploaded successfully',
filename: hashedFilename,
- unhashedFilename: unhashedFilename
+ unhashedFilename: unhashedFilename,
+ color
});
} catch (err: any) {
// Re-throw errors that already have status codes
diff --git a/src/routes/api/[recipeLang=recipeLang]/img/delete/+server.ts b/src/routes/api/[recipeLang=recipeLang]/img/delete/+server.ts
index 65b9706..326d247 100644
--- a/src/routes/api/[recipeLang=recipeLang]/img/delete/+server.ts
+++ b/src/routes/api/[recipeLang=recipeLang]/img/delete/+server.ts
@@ -17,7 +17,7 @@ export const POST = (async ({ request, locals}) => {
const basename = data.name || hashedFilename.replace(/\.[a-f0-9]{8}\.webp$/, '').replace(/\.webp$/, '');
const unhashedFilename = basename + '.webp';
- [ "full", "thumb", "placeholder"].forEach((folder) => {
+ [ "full", "thumb"].forEach((folder) => {
// Delete hashed version
unlink(path.join(IMAGE_DIR, "rezepte", folder, hashedFilename), (e) => {
if(e) console.warn(`Could not delete hashed: ${folder}/${hashedFilename}`, e);
diff --git a/src/routes/api/[recipeLang=recipeLang]/img/mv/+server.ts b/src/routes/api/[recipeLang=recipeLang]/img/mv/+server.ts
index c50f120..acb602a 100644
--- a/src/routes/api/[recipeLang=recipeLang]/img/mv/+server.ts
+++ b/src/routes/api/[recipeLang=recipeLang]/img/mv/+server.ts
@@ -26,7 +26,7 @@ export const POST = (async ({ request, locals}) => {
newFilename = data.new_name + ".webp";
}
- [ "full", "thumb", "placeholder"].forEach((folder) => {
+ [ "full", "thumb"].forEach((folder) => {
const old_path = path.join(IMAGE_DIR, "rezepte", folder, oldFilename)
rename(old_path, path.join(IMAGE_DIR, "rezepte", folder, newFilename), (e) => {
console.log(e)
diff --git a/src/routes/api/[recipeLang=recipeLang]/items/[name]/+server.ts b/src/routes/api/[recipeLang=recipeLang]/items/[name]/+server.ts
index 9e44d77..da50f2d 100644
--- a/src/routes/api/[recipeLang=recipeLang]/items/[name]/+server.ts
+++ b/src/routes/api/[recipeLang=recipeLang]/items/[name]/+server.ts
@@ -142,6 +142,7 @@ export const GET: RequestHandler = async ({ params }) => {
mediapath: img.mediapath,
alt: translatedImages[index]?.alt || img.alt || '',
caption: translatedImages[index]?.caption || img.caption || '',
+ color: img.color || '',
}));
}
diff --git a/src/routes/api/recalculate-image-colors/+server.ts b/src/routes/api/recalculate-image-colors/+server.ts
new file mode 100644
index 0000000..1bda546
--- /dev/null
+++ b/src/routes/api/recalculate-image-colors/+server.ts
@@ -0,0 +1,159 @@
+import { json, error } from '@sveltejs/kit';
+import type { RequestHandler } from './$types';
+import { Recipe } from '$models/Recipe.js';
+import { IMAGE_DIR } from '$env/static/private';
+import { extractDominantColor } from '$utils/imageProcessing';
+import { join } from 'path';
+import { access, constants } from 'fs/promises';
+
+export const POST: RequestHandler = async ({ request, locals }) => {
+ const session = await locals.auth();
+ if (!session?.user) {
+ throw error(401, 'Unauthorized');
+ }
+
+ try {
+ const body = await request.json();
+ const { filter = 'missing', limit = 50 } = body;
+
+ let query: any = { images: { $exists: true, $ne: [] } };
+
+ if (filter === 'missing') {
+ query = {
+ images: {
+ $elemMatch: {
+ mediapath: { $exists: true },
+ $or: [{ color: { $exists: false } }, { color: '' }],
+ },
+ },
+ };
+ }
+
+ const recipes = await Recipe.find(query).limit(limit);
+
+ if (recipes.length === 0) {
+ return json({
+ success: true,
+ processed: 0,
+ message: 'No recipes found matching criteria',
+ });
+ }
+
+ const results: Array<{
+ shortName: string;
+ name: string;
+ color: string;
+ status: 'ok' | 'error';
+ error?: string;
+ }> = [];
+
+ for (const recipe of recipes) {
+ const image = recipe.images[0];
+ if (!image?.mediapath) continue;
+
+ // Try unhashed filename first (always exists), fall back to hashed
+ const basename = image.mediapath
+ .replace(/\.[a-f0-9]{8}\.webp$/, '')
+ .replace(/\.webp$/, '');
+ const unhashedFilename = basename + '.webp';
+
+ const candidates = [
+ join(IMAGE_DIR, 'rezepte', 'full', unhashedFilename),
+ join(IMAGE_DIR, 'rezepte', 'full', image.mediapath),
+ join(IMAGE_DIR, 'rezepte', 'thumb', unhashedFilename),
+ join(IMAGE_DIR, 'rezepte', 'thumb', image.mediapath),
+ ];
+
+ let imagePath: string | null = null;
+ for (const candidate of candidates) {
+ try {
+ await access(candidate, constants.R_OK);
+ imagePath = candidate;
+ break;
+ } catch {
+ // try next
+ }
+ }
+
+ if (!imagePath) {
+ results.push({
+ shortName: recipe.short_name,
+ name: recipe.name,
+ color: '',
+ status: 'error',
+ error: 'Image file not found on disk',
+ });
+ continue;
+ }
+
+ try {
+ const color = await extractDominantColor(imagePath);
+ recipe.images[0].color = color;
+ await recipe.save();
+
+ results.push({
+ shortName: recipe.short_name,
+ name: recipe.name,
+ color,
+ status: 'ok',
+ });
+ } catch (err) {
+ console.error(`Failed to extract color for ${recipe.short_name}:`, err);
+ results.push({
+ shortName: recipe.short_name,
+ name: recipe.name,
+ color: '',
+ status: 'error',
+ error: err instanceof Error ? err.message : 'Unknown error',
+ });
+ }
+ }
+
+ return json({
+ success: true,
+ processed: results.filter(r => r.status === 'ok').length,
+ failed: results.filter(r => r.status === 'error').length,
+ results,
+ });
+ } catch (err) {
+ console.error('Error in bulk color recalculation:', err);
+
+ if (err instanceof Error && 'status' in err) {
+ throw err;
+ }
+
+ throw error(500, err instanceof Error ? err.message : 'Failed to recalculate colors');
+ }
+};
+
+export const GET: RequestHandler = async ({ locals }) => {
+ const session = await locals.auth();
+ if (!session?.user) {
+ throw error(401, 'Unauthorized');
+ }
+
+ try {
+ const totalWithImages = await Recipe.countDocuments({
+ images: { $exists: true, $ne: [] },
+ });
+
+ const missingColor = await Recipe.countDocuments({
+ images: {
+ $elemMatch: {
+ mediapath: { $exists: true },
+ $or: [{ color: { $exists: false } }, { color: '' }],
+ },
+ },
+ });
+
+ const withColor = totalWithImages - missingColor;
+
+ return json({
+ totalWithImages,
+ missingColor,
+ withColor,
+ });
+ } catch (err) {
+ throw error(500, 'Failed to fetch statistics');
+ }
+};
diff --git a/src/service-worker.ts b/src/service-worker.ts
index 04f0f1b..cb36bcc 100644
--- a/src/service-worker.ts
+++ b/src/service-worker.ts
@@ -113,10 +113,10 @@ sw.addEventListener('fetch', (event) => {
return;
}
- // Handle recipe images (thumbnails, full images, and placeholders)
+ // Handle recipe images (thumbnails and full images)
if (
url.pathname.startsWith('/static/rezepte/') &&
- (url.pathname.includes('/thumb/') || url.pathname.includes('/full/') || url.pathname.includes('/placeholder/'))
+ (url.pathname.includes('/thumb/') || url.pathname.includes('/full/'))
) {
event.respondWith(
(async () => {
@@ -137,8 +137,8 @@ sw.addEventListener('fetch', (event) => {
}
return response;
} catch {
- // Network failed - try to serve thumbnail as fallback for full/placeholder
- if (url.pathname.includes('/full/') || url.pathname.includes('/placeholder/')) {
+ // Network failed - try to serve thumbnail as fallback for full
+ if (url.pathname.includes('/full/')) {
// Extract filename and try to find cached thumbnail
const filename = url.pathname.split('/').pop();
if (filename) {
diff --git a/src/types/types.ts b/src/types/types.ts
index 5f84e2a..8ceadb2 100644
--- a/src/types/types.ts
+++ b/src/types/types.ts
@@ -123,7 +123,8 @@ export type RecipeModelType = {
images?: [{
mediapath: string;
alt: string;
- caption?: string
+ caption?: string;
+ color?: string;
}];
description: string;
tags: [string];
@@ -164,6 +165,7 @@ export type BriefRecipeType = {
mediapath: string;
alt: string;
caption?: string;
+ color?: string;
}]
description: string;
tags: [string];
diff --git a/src/utils/imageProcessing.ts b/src/utils/imageProcessing.ts
index 0960ffa..b8e7300 100644
--- a/src/utils/imageProcessing.ts
+++ b/src/utils/imageProcessing.ts
@@ -3,18 +3,107 @@ import sharp from 'sharp';
import { generateImageHashFromBuffer, getHashedFilename } from '$utils/imageHash';
import { validateImageFile } from '$utils/imageValidation';
+// --- sRGB <-> linear RGB <-> OKLAB color conversions ---
+
+function srgbToLinear(c: number): number {
+ return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
+}
+
+function linearToSrgb(c: number): number {
+ return c <= 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
+}
+
+function linearRgbToOklab(r: number, g: number, b: number): [number, number, number] {
+ const l_ = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b;
+ const m_ = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;
+ const s_ = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;
+ const l = Math.cbrt(l_);
+ const m = Math.cbrt(m_);
+ const s = Math.cbrt(s_);
+ return [
+ 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s,
+ 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s,
+ 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s,
+ ];
+}
+
+function oklabToLinearRgb(L: number, a: number, b: number): [number, number, number] {
+ const l = L + 0.3963377774 * a + 0.2158037573 * b;
+ const m = L - 0.1055613458 * a - 0.0638541728 * b;
+ const s = L - 0.0894841775 * a - 1.2914855480 * b;
+ const l3 = l * l * l;
+ const m3 = m * m * m;
+ const s3 = s * s * s;
+ return [
+ +4.0767416621 * l3 - 3.3077115913 * m3 + 0.2309699292 * s3,
+ -1.2684380046 * l3 + 2.6097574011 * m3 - 0.3413193965 * s3,
+ -0.0041960863 * l3 - 0.7034186147 * m3 + 1.7076147010 * s3,
+ ];
+}
+
/**
- * Process and save recipe image with multiple versions (full, thumb, placeholder)
+ * Extract the perceptually dominant color from an image buffer.
+ * Averages pixels in OKLAB space with a 2D Gaussian kernel biased toward the center.
+ * Returns a hex string like "#a1b2c3".
+ */
+export async function extractDominantColor(input: Buffer | string): Promise {
+ const { data, info } = await sharp(input)
+ .resize(50, 50, { fit: 'cover' })
+ .removeAlpha()
+ .raw()
+ .toBuffer({ resolveWithObject: true });
+
+ const { width, height } = info;
+ const cx = (width - 1) / 2;
+ const cy = (height - 1) / 2;
+ const sigmaX = 0.3 * width;
+ const sigmaY = 0.3 * height;
+
+ let wL = 0, wa = 0, wb = 0, wSum = 0;
+
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const i = (y * width + x) * 3;
+ // Gaussian weight based on distance from center
+ const dx = x - cx;
+ const dy = y - cy;
+ const w = Math.exp(-0.5 * ((dx * dx) / (sigmaX * sigmaX) + (dy * dy) / (sigmaY * sigmaY)));
+
+ // sRGB [0-255] -> linear [0-1] -> OKLAB
+ const lr = srgbToLinear(data[i] / 255);
+ const lg = srgbToLinear(data[i + 1] / 255);
+ const lb = srgbToLinear(data[i + 2] / 255);
+ const [L, a, b] = linearRgbToOklab(lr, lg, lb);
+
+ wL += w * L;
+ wa += w * a;
+ wb += w * b;
+ wSum += w;
+ }
+ }
+
+ // Average in OKLAB, convert back to sRGB
+ const [rLin, gLin, bLin] = oklabToLinearRgb(wL / wSum, wa / wSum, wb / wSum);
+ const r = Math.round(Math.min(1, Math.max(0, linearToSrgb(rLin))) * 255);
+ const g = Math.round(Math.min(1, Math.max(0, linearToSrgb(gLin))) * 255);
+ const b = Math.round(Math.min(1, Math.max(0, linearToSrgb(bLin))) * 255);
+
+ return '#' + ((1 << 24) | (r << 16) | (g << 8) | b).toString(16).slice(1);
+}
+
+/**
+ * Process and save recipe image with multiple versions (full, thumb)
+ * and extract dominant color.
* @param file - The image File object
* @param name - The base name for the image (usually recipe short_name)
* @param imageDir - The base directory where images are stored
- * @returns Object with hashedFilename and unhashedFilename
+ * @returns Object with hashedFilename, unhashedFilename, and dominant color
*/
export async function processAndSaveRecipeImage(
file: File,
name: string,
imageDir: string
-): Promise<{ filename: string; unhashedFilename: string }> {
+): Promise<{ filename: string; unhashedFilename: string; color: string }> {
console.log('[ImageProcessing] Starting image processing for:', {
fileName: file.name,
recipeName: name,
@@ -58,7 +147,7 @@ export async function processAndSaveRecipeImage(
await sharp(fullBuffer).toFile(fullHashedPath);
await sharp(fullBuffer).toFile(fullUnhashedPath);
- console.log('[ImageProcessing] Full size images saved ✓');
+ console.log('[ImageProcessing] Full size images saved');
// Save thumbnail (800px width) - both hashed and unhashed versions
console.log('[ImageProcessing] Generating thumbnail (800px)...');
@@ -75,28 +164,17 @@ export async function processAndSaveRecipeImage(
await sharp(thumbBuffer).toFile(thumbHashedPath);
await sharp(thumbBuffer).toFile(thumbUnhashedPath);
- console.log('[ImageProcessing] Thumbnail images saved ✓');
+ console.log('[ImageProcessing] Thumbnail images saved');
- // Save placeholder (20px width) - both hashed and unhashed versions
- console.log('[ImageProcessing] Generating placeholder (20px)...');
- const placeholderBuffer = await sharp(buffer)
- .resize({ width: 20 })
- .toFormat('webp')
- .webp({ quality: 60 })
- .toBuffer();
- console.log('[ImageProcessing] Placeholder buffer created, size:', placeholderBuffer.length, 'bytes');
+ // Extract dominant color
+ console.log('[ImageProcessing] Extracting dominant color...');
+ const color = await extractDominantColor(buffer);
+ console.log('[ImageProcessing] Dominant color:', color);
- const placeholderHashedPath = path.join(imageDir, 'rezepte', 'placeholder', hashedFilename);
- const placeholderUnhashedPath = path.join(imageDir, 'rezepte', 'placeholder', unhashedFilename);
- console.log('[ImageProcessing] Saving placeholder to:', { placeholderHashedPath, placeholderUnhashedPath });
-
- await sharp(placeholderBuffer).toFile(placeholderHashedPath);
- await sharp(placeholderBuffer).toFile(placeholderUnhashedPath);
- console.log('[ImageProcessing] Placeholder images saved ✓');
-
- console.log('[ImageProcessing] All image versions processed and saved successfully ✓');
+ console.log('[ImageProcessing] All image versions processed and saved successfully');
return {
filename: hashedFilename,
- unhashedFilename: unhashedFilename
+ unhashedFilename: unhashedFilename,
+ color
};
}