feat: image optimization — client-side resize + server-side thumbnails

Avatars/banners now resize to max 512px/1920px and convert to WebP before
upload (zero server cost). Chat image uploads generate an 800px-wide WebP
thumbnail via Sharp; the feed shows the thumbnail, click opens the full-res
original. Adds lazy loading to avatars. Federation-compatible: remote
instances without this feature fall back gracefully.
This commit is contained in:
Jannis Braun
2026-03-13 16:44:14 +01:00
parent 12b450b7b9
commit 3e97c2b0f5
19 changed files with 449 additions and 20 deletions
+66
View File
@@ -0,0 +1,66 @@
import path from 'path';
import sharp from 'sharp';
const RESIZABLE_MIMETYPES = new Set([
'image/jpeg',
'image/png',
'image/webp',
'image/gif',
'image/avif',
'image/tiff',
]);
const THUMBNAIL_MAX_WIDTH = 800;
const THUMBNAIL_QUALITY = 80;
/**
* Derive a deterministic thumbnail filename from the original.
* e.g. "123456789.png" → "123456789_thumb.webp"
*/
export function thumbFilename(original: string): string {
const parsed = path.parse(original);
return `${parsed.name}_thumb.webp`;
}
/** Check if the given mimetype is a resizable image format. */
export function isResizableImage(mimetype: string): boolean {
return RESIZABLE_MIMETYPES.has(mimetype);
}
/**
* Generate a WebP thumbnail for the given image file.
* Returns the thumbnail filename on success, or null if:
* - The image is already ≤ THUMBNAIL_MAX_WIDTH px wide
* - An error occurs (upload still succeeds without thumbnail)
*/
export async function generateThumbnail(
originalPath: string,
mimetype: string,
uploadDir: string,
): Promise<string | null> {
if (!isResizableImage(mimetype)) return null;
try {
const image = sharp(originalPath);
const metadata = await image.metadata();
// Skip if the original is already small enough
if (!metadata.width || metadata.width <= THUMBNAIL_MAX_WIDTH) {
return null;
}
const originalFilename = path.basename(originalPath);
const thumbName = thumbFilename(originalFilename);
const thumbPath = path.join(uploadDir, thumbName);
await sharp(originalPath)
.resize({ width: THUMBNAIL_MAX_WIDTH, withoutEnlargement: true })
.webp({ quality: THUMBNAIL_QUALITY })
.toFile(thumbPath);
return thumbName;
} catch (err) {
console.error('Thumbnail generation failed (non-fatal):', err);
return null;
}
}