Skip to content

Build your personal knowledge base with Trilium Notes

refactor(link-preview): resize the cover image through the image provider

Elian Dorand85d4b7c3776
diff --git a/apps/build-docs/src/build-docs.ts b/apps/build-docs/src/build-docs.ts
index 8cd8800e82..1305eb9254 100644
--- a/apps/build-docs/src/build-docs.ts
+++ b/apps/build-docs/src/build-docs.ts
@@ -44,7 +44,8 @@ const stubImageProvider: ImageProvider = {
},
compressImage: async () => ({ compressed: false, reason: "unsupported-platform" }),
planCompression: async () => ({ skip: "unsupported-platform" as const, decodeCost: null }),
- compressionConcurrency: () => 1
+ compressionConcurrency: () => 1,
+ resizeForPreview: async () => ({ resized: false, reason: "unsupported-platform" as const })
};
import { ZipArchive } from "archiver";
import { execSync } from "child_process";
diff --git a/apps/server/src/routes/api/link_embed.ts b/apps/server/src/routes/api/link_embed.ts
index cc58bd41ce..16716e0592 100644
--- a/apps/server/src/routes/api/link_embed.ts
+++ b/apps/server/src/routes/api/link_embed.ts
@@ -8,10 +8,10 @@ import {
import { getLog, imageService, ValidationError } from "@triliumnext/core";
import { trimIcoToSmallestEntry } from "@triliumnext/core/src/services/ico.js";
import { storePictureBytes } from "@triliumnext/core/src/services/image_download.js";
-import { inspectImage, UNKNOWN_FORMAT } from "@triliumnext/core/src/services/image_inspect.js";
+import { type InspectedImage, inspectImage, UNKNOWN_FORMAT } from "@triliumnext/core/src/services/image_inspect.js";
+import { getImageProvider } from "@triliumnext/core/src/services/image_provider.js";
import { findPageDescription } from "@triliumnext/core/src/services/page_description.js";
import type { Request } from "express";
-import { Jimp } from "jimp";
import { parse } from "node-html-parser";
import { safeFetch, validateUrl } from "../../services/safe_fetch.js";
@@ -270,46 +270,47 @@ async function downloadPreviewImage(imageUrl: string, minSourceDimension = 0): P
if (!downloaded) return undefined;
const { bytes, contentType } = downloaded;
+ const inspected = inspectImage(bytes);
const isSmallEnoughToKeepVerbatim = bytes.byteLength <= MAX_VERBATIM_IMAGE_SIZE;
- // An SVG scales natively, so it is kept as-is rather than rasterised (Jimp cannot read it anyway),
- // and it satisfies any minimum dimension by definition. The sniff reads the opening bytes only,
- // so it costs the same whatever the file weighs.
- if (contentType.includes("svg") || inspectImage(bytes).format === "svg") {
+ // An SVG scales natively, so it is kept as-is rather than rasterised, and it satisfies any
+ // minimum dimension by definition. The sniff reads the opening bytes only, so it costs the same
+ // whatever the file weighs.
+ if (contentType.includes("svg") || inspected.format === "svg") {
return isSmallEnoughToKeepVerbatim ? { bytes } : undefined;
}
- try {
- const image = await Jimp.read(Buffer.from(bytes));
-
- if (Math.max(image.bitmap.width, image.bitmap.height) < minSourceDimension) {
- return undefined;
- }
+ if (minSourceDimension && !isAtLeast(inspected, minSourceDimension)) {
+ return undefined;
+ }
- // Only ever scale down: scaleToFit() would happily enlarge a smaller image.
- if (image.bitmap.width > IMAGE_MAX_DIMENSION || image.bitmap.height > IMAGE_MAX_DIMENSION) {
- image.scaleToFit({ w: IMAGE_MAX_DIMENSION, h: IMAGE_MAX_DIMENSION });
- }
+ const resized = await getImageProvider().resizeForPreview(bytes, {
+ maxEdge: IMAGE_MAX_DIMENSION,
+ jpegQuality: IMAGE_JPEG_QUALITY
+ });
- // hasAlpha() inspects the pixels, not just the channel, so an opaque PNG still takes the
- // JPEG path. An animated GIF/WebP collapses to its first frame, which is fine for a thumbnail.
- return image.hasAlpha()
- ? { bytes: new Uint8Array(await image.getBuffer("image/png")) }
- : { bytes: new Uint8Array(await image.getBuffer("image/jpeg", { quality: IMAGE_JPEG_QUALITY })) };
- } catch (e: unknown) {
- // Jimp bundles decoders for PNG/JPEG/GIF/BMP/TIFF only, so a WebP or AVIF lands here. Keep
- // the original bytes when they are small enough — unresized, but still not hotlinked. The
- // bytes are asked what they are, the same way a favicon's are, so that an error page served
- // in place of the image (an undecodable response that is not an image at all) is dropped
- // rather than embedded. A caller that requires a minimum size gets nothing: undecodable
- // means unverifiable.
- // The URL is deliberately left out of the log: it is the user's private browsing, and a
- // pasted link can carry a one-time token in its path or query. The timestamp is enough to
- // match a log line against the paste that caused it.
- getLog().info(`Could not decode a link preview image: ${e}`);
-
- return isSmallEnoughToKeepVerbatim && !minSourceDimension ? asPicture(bytes) : undefined;
+ if (resized.resized) {
+ return { bytes: resized.bytes };
}
+
+ // Nothing scaled it — an undecodable format (WebP, AVIF) where there is a decoder, anything at
+ // all where there is not. Keep the original bytes if they are small enough: unresized, but
+ // still stored rather than hotlinked, which is the property that matters. They are asked what
+ // they are on the way past, so an error page served in place of a picture is dropped rather
+ // than embedded.
+ return isSmallEnoughToKeepVerbatim ? asPicture(bytes) : undefined;
+}
+
+/**
+ * Whether a picture is at least `minEdge` across, read from its header.
+ *
+ * Header rather than decode, so the answer costs nothing and is available on a runtime that has no
+ * decoder at all — which is the point: the alternative was to decode purely to measure, and to
+ * treat every picture that would not decode as too small. A header that does not say is treated as
+ * too small, since unverified is not the same as large enough.
+ */
+function isAtLeast({ width, height }: InspectedImage, minEdge: number): boolean {
+ return width !== null && height !== null && Math.max(width, height) >= minEdge;
}
/**
diff --git a/apps/server/src/services/image_codec.ts b/apps/server/src/services/image_codec.ts
index c825b8678d..63c7489506 100644
--- a/apps/server/src/services/image_codec.ts
+++ b/apps/server/src/services/image_codec.ts
@@ -12,7 +12,7 @@
import { IMAGE_COMPRESSIBLE_FORMATS, type ImageCompressionSkipReason } from "@triliumnext/commons";
import { type InspectedImage, inspectImage } from "@triliumnext/core/src/services/image_inspect.js";
-import type { ImageCompressionOutcome, ImageCompressionRequest, ImageFormat } from "@triliumnext/core/src/services/image_provider.js";
+import type { ImageCompressionOutcome, ImageCompressionRequest, ImageFormat, PreviewResizeOutcome, PreviewResizeRequest } from "@triliumnext/core/src/services/image_provider.js";
import { estimateJpegQuality } from "@triliumnext/core/src/services/jpeg_quality.js";
import imageType from "image-type";
import isAnimated from "is-animated";
@@ -442,3 +442,49 @@ export async function compressImageBytes(
return { compressed: true, buffer: result, format: toJpeg ? JPEG_FORMAT : PNG_FORMAT };
}
+/**
+ * Scales a link preview's cover image down to `maxEdge` and re-encodes it.
+ *
+ * The bytes make a round trip — downloaded and stored in the same breath — so the reduction happens
+ * here rather than being left to the generic compression pass: a 5MB `og:image` has no business
+ * being carried through a pipeline sized for the user's own photographs to become a thumbnail
+ * nobody will see above a couple of hundred pixels.
+ *
+ * Transparency survives by re-encoding to PNG only where the picture actually has non-opaque pixels;
+ * an opaque one becomes a JPEG, which is several times smaller.
+ *
+ * Answers `undecodable` rather than throwing when Jimp cannot read the bytes — it bundles decoders
+ * for PNG/JPEG/GIF/BMP/TIFF only, so a WebP or an AVIF lands there, as does an error page served
+ * where a picture should have been. Saying so is enough; what a preview does without its picture is
+ * not this function's business.
+ */
+export async function resizePreviewImage(
+ bytes: Uint8Array,
+ { maxEdge, jpegQuality }: PreviewResizeRequest,
+ log: CodecLog = () => {}
+): Promise<PreviewResizeOutcome> {
+ try {
+ const image = await decodeImage(bytes);
+
+ // Only ever down: scaleToFit() would happily enlarge a smaller picture.
+ if (image.bitmap.width > maxEdge || image.bitmap.height > maxEdge) {
+ image.scaleToFit({ w: maxEdge, h: maxEdge });
+ }
+
+ // hasAlpha() inspects the pixels rather than just the channel, so an opaque PNG still takes
+ // the JPEG path. An animated GIF or WebP collapses to its first frame, which is all a
+ // thumbnail wanted of it.
+ const encoded = image.hasAlpha()
+ ? await image.getBuffer("image/png")
+ : await image.getBuffer("image/jpeg", { quality: jpegQuality });
+
+ return { resized: true, bytes: new Uint8Array(encoded) };
+ } catch (e: unknown) {
+ // The address is deliberately left out of the line: it is the user's private browsing, and a
+ // pasted link can carry a one-time token in its path or query.
+ log(`Could not decode a link preview image: ${e}`, true);
+
+ return { resized: false, reason: "undecodable" };
+ }
+}
+
diff --git a/apps/server/src/services/image_codec_preview.spec.ts b/apps/server/src/services/image_codec_preview.spec.ts
new file mode 100644
index 0000000000..1f31a953b2
--- /dev/null
+++ b/apps/server/src/services/image_codec_preview.spec.ts
@@ -0,0 +1,75 @@
+import { Jimp } from "jimp";
+import { describe, expect, it } from "vitest";
+
+import { resizePreviewImage } from "./image_codec.js";
+
+const REQUEST = { maxEdge: 256, jpegQuality: 75 };
+
+async function png(width: number, height: number, color = 0xff0000ff) {
+ return new Uint8Array(await new Jimp({ width, height, color }).getBuffer("image/png"));
+}
+
+async function decoded(bytes: Uint8Array) {
+ return await Jimp.fromBuffer(Buffer.from(bytes));
+}
+
+describe("resizePreviewImage", () => {
+ it("scales a large picture down to the longest edge asked for, keeping its proportions", async () => {
+ const result = await resizePreviewImage(await png(1000, 500), REQUEST);
+
+ expect(result.resized).toBe(true);
+ if (!result.resized) return;
+
+ const image = await decoded(result.bytes);
+ expect(image.bitmap.width).toBe(256);
+ expect(image.bitmap.height).toBe(128);
+ });
+
+ it("leaves a picture already smaller than the ceiling at the size it came", async () => {
+ const result = await resizePreviewImage(await png(64, 48), REQUEST);
+
+ expect(result.resized).toBe(true);
+ if (!result.resized) return;
+
+ const image = await decoded(result.bytes);
+ expect(image.bitmap.width).toBe(64);
+ expect(image.bitmap.height).toBe(48);
+ });
+
+ /**
+ * The choice of encoding is by what the pixels actually are, not by what the format allows: a
+ * PNG with nothing transparent in it is several times smaller as a JPEG, and a card thumbnail
+ * is not where that saving should be passed up.
+ */
+ it("re-encodes an opaque picture to JPEG and a transparent one to PNG", async () => {
+ const opaque = await resizePreviewImage(await png(300, 300, 0x336699ff), REQUEST);
+ const transparent = await resizePreviewImage(await png(300, 300, 0x33669900), REQUEST);
+
+ expect(opaque.resized && (await decoded(opaque.bytes)).mime).toBe("image/jpeg");
+ expect(transparent.resized && (await decoded(transparent.bytes)).mime).toBe("image/png");
+ });
+
+ it("says so rather than throwing when the bytes are not a picture it can read", async () => {
+ // An error page served where a picture should have been — the case this has to survive.
+ const html = new TextEncoder().encode("<!doctype html><title>404</title>");
+
+ await expect(resizePreviewImage(html, REQUEST)).resolves.toEqual({
+ resized: false,
+ reason: "undecodable"
+ });
+ });
+
+ it("passes the reason to the log it was given, and manages without one", async () => {
+ const lines: string[] = [];
+ await resizePreviewImage(new Uint8Array([ 1, 2, 3 ]), REQUEST, (message) => lines.push(message));
+
+ expect(lines).toHaveLength(1);
+ expect(lines[0]).toMatch(/Could not decode a link preview image/);
+ // The address never appears: a pasted link can carry a one-time token in its query.
+ expect(lines[0]).not.toMatch(/http/);
+
+ await expect(resizePreviewImage(new Uint8Array([ 1, 2, 3 ]), REQUEST)).resolves.toMatchObject({
+ resized: false
+ });
+ });
+});
diff --git a/apps/server/src/services/image_compression.spec.ts b/apps/server/src/services/image_compression.spec.ts
index 8c64f8d8ad..6192d51fec 100644
--- a/apps/server/src/services/image_compression.spec.ts
+++ b/apps/server/src/services/image_compression.spec.ts
@@ -533,10 +533,7 @@ describe("compression parameters", () => {
// The header pass is an optimization of the read, never a precondition for it — so when it
// cannot answer, the run must go the long way round rather than report a failure.
initImageProvider({
- getImageType: (buffer) => real.getImageType(buffer),
- processImage: (buffer, name, shrink) => real.processImage(buffer, name, shrink),
- compressImage: (buffer, compressionRequest) => real.compressImage(buffer, compressionRequest),
- compressionConcurrency: () => real.compressionConcurrency(),
+ ...real,
planCompression: () => Promise.reject(new Error("planner unavailable"))
});
@@ -567,9 +564,7 @@ describe("compression parameters", () => {
let compressedSoFar = 0;
initImageProvider({
- getImageType: (buffer) => real.getImageType(buffer),
- processImage: (buffer, name, shrink) => real.processImage(buffer, name, shrink),
- planCompression: (header, req) => real.planCompression(header, req),
+ ...real,
compressionConcurrency: () => 1,
compressImage: async (buffer, req) => {
const outcome = await real.compressImage(buffer, req);
@@ -898,10 +893,7 @@ async function whileCompressing<T>(interfere: () => void, request: () => Promise
const real = getImageProvider();
initImageProvider({
- getImageType: (buffer) => real.getImageType(buffer),
- processImage: (buffer, originalName, shrink) => real.processImage(buffer, originalName, shrink),
- planCompression: (header, compressionRequest) => real.planCompression(header, compressionRequest),
- compressionConcurrency: () => real.compressionConcurrency(),
+ ...real,
compressImage: (buffer, compressionRequest) => {
interfere();
return real.compressImage(buffer, compressionRequest);
diff --git a/apps/server/src/services/image_provider.ts b/apps/server/src/services/image_provider.ts
index c9902ff39c..fe6d3993b0 100644
--- a/apps/server/src/services/image_provider.ts
+++ b/apps/server/src/services/image_provider.ts
@@ -7,7 +7,7 @@
*/
import { getLog, imageCompressionService, options as optionService } from "@triliumnext/core";
-import type { ImageCompressionOutcome, ImageCompressionPlan, ImageCompressionRequest, ImageFormat, ImageProvider, ProcessedImage } from "@triliumnext/core/src/services/image_provider.js";
+import type { ImageCompressionOutcome, ImageCompressionPlan, ImageCompressionRequest, ImageFormat, ImageProvider, PreviewResizeOutcome, PreviewResizeRequest, ProcessedImage } from "@triliumnext/core/src/services/image_provider.js";
import { createConcurrencyGate } from "./concurrency_gate.js";
import {
@@ -16,7 +16,8 @@ import {
decodeCostOf,
detectSvg,
getImageTypeFromBuffer,
- planFromBytes
+ planFromBytes,
+ resizePreviewImage
} from "./image_codec.js";
import { compressInWorker, compressionConcurrency } from "./image_worker_pool.js";
@@ -124,5 +125,9 @@ export const serverImageProvider: ImageProvider = {
return offThread ?? compressImageBytes(buffer, request, toBackendLog);
},
- compressionConcurrency
+ compressionConcurrency,
+
+ async resizeForPreview(bytes: Uint8Array, request: PreviewResizeRequest): Promise<PreviewResizeOutcome> {
+ return await resizePreviewImage(bytes, request, toBackendLog);
+ }
};
diff --git a/apps/standalone/src/services/image_provider.ts b/apps/standalone/src/services/image_provider.ts
index 3e6e920ddf..9703ad0229 100644
--- a/apps/standalone/src/services/image_provider.ts
+++ b/apps/standalone/src/services/image_provider.ts
@@ -4,7 +4,7 @@
* Images are saved as-is without resizing.
*/
-import type { ImageCompressionOutcome, ImageCompressionPlan, ImageFormat, ImageProvider, ProcessedImage } from "@triliumnext/core";
+import type { ImageCompressionOutcome, ImageCompressionPlan, ImageFormat, ImageProvider, PreviewResizeOutcome, ProcessedImage } from "@triliumnext/core";
import { inspectImage, UNKNOWN_FORMAT } from "@triliumnext/core/src/services/image_inspect.js";
/**
@@ -47,5 +47,18 @@ export const standaloneImageProvider: ImageProvider = {
// Settled before an image is so much as weighed: nothing here is going to compress it
// whatever its header says, so a run over a tree reads none of them.
return { skip: "unsupported-platform", decodeCost: null };
+ },
+
+ /**
+ * Declined for the same reason as everything else on this runtime: there is no decoder to scale
+ * a picture with.
+ *
+ * The preview is not lost to it. The caller keeps a cover image that is already small enough to
+ * store as it came, and shows a preview without a picture where it is not — which is exactly
+ * what the server does for a WebP its own decoder cannot read, so this is a path already
+ * travelled rather than a new kind of degradation.
+ */
+ async resizeForPreview(): Promise<PreviewResizeOutcome> {
+ return { resized: false, reason: "unsupported-platform" };
}
};
diff --git a/packages/trilium-core/src/services/image_provider.spec.ts b/packages/trilium-core/src/services/image_provider.spec.ts
index 54a216f58e..e6e3cad67e 100644
--- a/packages/trilium-core/src/services/image_provider.spec.ts
+++ b/packages/trilium-core/src/services/image_provider.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
-import type { ImageCompressionOutcome, ImageProvider, ProcessedImage } from "./image_provider.js";
+import type { ImageCompressionOutcome, ImageProvider, PreviewResizeOutcome, ProcessedImage } from "./image_provider.js";
describe("image provider (core)", () => {
// The core bootstrap installs a real image provider, so to exercise the
@@ -22,7 +22,11 @@ describe("image provider (core)", () => {
reason: "no-gain"
})),
planCompression: vi.fn(async () => ({ decodeCost: null })),
- compressionConcurrency: vi.fn(() => 1)
+ compressionConcurrency: vi.fn(() => 1),
+ resizeForPreview: vi.fn(async (): Promise<PreviewResizeOutcome> => ({
+ resized: false,
+ reason: "unsupported-platform"
+ }))
};
mod.initImageProvider(fake);
expect(mod.getImageProvider()).toBe(fake);
diff --git a/packages/trilium-core/src/services/image_provider.ts b/packages/trilium-core/src/services/image_provider.ts
index 618791e33f..9fc66f3a64 100644
--- a/packages/trilium-core/src/services/image_provider.ts
+++ b/packages/trilium-core/src/services/image_provider.ts
@@ -93,8 +93,38 @@ export interface ImageProvider {
* @param request - Fully resolved compression parameters
*/
planCompression(header: Uint8Array, request: ImageCompressionRequest): Promise<ImageCompressionPlan>;
+
+ /**
+ * Scales a link preview's cover image down to `maxEdge` and re-encodes it, or declines.
+ *
+ * Separate from {@link compressImage} because the two want opposite things. Compression is
+ * offered an image the user chose to keep and tries to make it cheaper without changing what it
+ * is; this is handed someone else's `og:image` — up to 5MB of it — and wants a thumbnail nobody
+ * will see above a couple of hundred pixels. Reusing the compression path would mean carrying
+ * the full picture through a pipeline sized for the user's own photographs, to produce something
+ * that is thrown away at the size this asks for anyway.
+ *
+ * Declining is a first-class answer, not a failure: a runtime with no decoder cannot do this at
+ * all, and the caller has a perfectly good fallback — keep the original bytes when they are
+ * small enough, and otherwise show the preview without a picture, which is what it does for an
+ * image the decoder cannot read either way.
+ */
+ resizeForPreview(bytes: Uint8Array, request: PreviewResizeRequest): Promise<PreviewResizeOutcome>;
+}
+
+/** How a preview's cover image is to be reduced. */
+export interface PreviewResizeRequest {
+ /** Longest edge to scale down to. Never up: a small picture is left at the size it came. */
+ maxEdge: number;
+ /** Quality for the JPEG an opaque image becomes; one with real transparency becomes a PNG. */
+ jpegQuality: number;
}
+/** Bytes to store in place of the original, or the reason there are none. */
+export type PreviewResizeOutcome =
+ | { resized: true; bytes: Uint8Array }
+ | { resized: false; reason: "undecodable" | "unsupported-platform" };
+
/** What a provider makes of an image from its header alone. */
export interface ImageCompressionPlan {
/** Set when the image is to be left alone, and why; absent when it has to be read in full. */