Skip to content

Build your personal knowledge base with Trilium Notes

core: add API to explicitly resize an image/the images of a note

Adorian Doranc2194f39f8cd
diff --git a/apps/build-docs/src/build-docs.ts b/apps/build-docs/src/build-docs.ts
index 50e829843b..a54bb50ca6 100644
--- a/apps/build-docs/src/build-docs.ts
+++ b/apps/build-docs/src/build-docs.ts
@@ -40,7 +40,8 @@ const stubImageProvider: ImageProvider = {
getImageType: () => null,
processImage: async () => {
throw new Error("Image processing not supported in build-docs");
- }
+ },
+ compressImage: async () => ({ compressed: false, reason: "unsupported-platform" })
};
import { ZipArchive } from "archiver";
import { execSync } from "child_process";
diff --git a/apps/server/src/services/image_compression.spec.ts b/apps/server/src/services/image_compression.spec.ts
new file mode 100644
index 0000000000..33c588d230
--- /dev/null
+++ b/apps/server/src/services/image_compression.spec.ts
@@ -0,0 +1,390 @@
+import type { ImageCompressionResponse } from "@triliumnext/commons";
+import { becca, cls, getSql, options } from "@triliumnext/core";
+import { createTextNote } from "@triliumnext/core/src/test/api_fixtures.js";
+import { CoreApiTester } from "@triliumnext/core/src/test/api_tester.js";
+import { Jimp } from "jimp";
+import { afterEach, beforeAll, describe, expect, it } from "vitest";
+
+/**
+ * Drives the on-demand image compression endpoints end to end: real notes and attachments in the
+ * in-memory database, the real core service, and the real JIMP-backed provider. Nothing is mocked,
+ * so what these assert is what a caller actually gets back — and, just as importantly, what is left
+ * behind in the database afterwards.
+ *
+ * This spec lives under `apps/server` rather than in core because compression only exists on this
+ * runtime; the standalone (WASM) build has no decoder, and core specs run under both.
+ */
+let api: CoreApiTester;
+
+/** A large noisy PNG: big enough that both converting and resizing it save real bytes. */
+let noisyPng: Uint8Array;
+/** An 8x8 solid PNG, which nothing can make smaller. */
+let smallPng: Uint8Array;
+/** A PNG signature followed by garbage: passes format detection, fails to decode. */
+let corruptPng: Uint8Array;
+
+beforeAll(async () => {
+ api = CoreApiTester.build();
+
+ const noisy = new Jimp({ width: 600, height: 400, color: 0x3366ccff });
+ for (let x = 0; x < 600; x++) {
+ for (let y = 0; y < 400; y++) {
+ const color = ((((x * 31 + y * 17) % 256) << 24) | (((x * 13 + y * 7) % 256) << 16) | (((x * 5 + y * 23) % 256) << 8) | 0xff) >>> 0;
+ noisy.setPixelColor(color, x, y);
+ }
+ }
+ noisyPng = new Uint8Array(await noisy.getBuffer("image/png"));
+
+ const small = new Jimp({ width: 8, height: 8, color: 0x3366ccff });
+ smallPng = new Uint8Array(await small.getBuffer("image/png"));
+
+ corruptPng = new Uint8Array(Buffer.concat([ Buffer.from(smallPng.slice(0, 50)), Buffer.alloc(400, 0xab) ]));
+}, 60000);
+
+afterEach(() => {
+ cls.init(() => {
+ options.setOption("imageMaxWidthHeight", "2000");
+ options.setOption("imageJpegQuality", "75");
+ });
+});
+
+describe("compress note images (POST /api/notes/:noteId/compress-images)", () => {
+ it("404s for a note that does not exist", async () => {
+ const res = await api.post("/api/notes/missingNote123/compress-images");
+
+ expect(res.status).toBe(404);
+ });
+
+ it("compresses an image note's own content and writes the new bytes and mime back", async () => {
+ const noteId = await createImageNote(noisyPng);
+
+ const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {
+ body: { convertLossless: true }
+ });
+
+ expect(res.status).toBe(200);
+ expect(res.body.compressedCount).toBe(1);
+ expect(res.body.skippedCount).toBe(0);
+ expect(res.body.savedSize).toBe(res.body.originalSize - res.body.newSize);
+ expect(res.body.savedSize).toBeGreaterThan(0);
+ expect(res.body.items[0]).toMatchObject({
+ entityType: "note",
+ entityId: noteId,
+ mime: "image/jpeg",
+ compressed: true
+ });
+
+ const stored = readNote(noteId);
+ expect(stored.mime).toBe("image/jpeg");
+ expect(stored.size).toBe(res.body.newSize);
+ expect(stored.size).toBeLessThan(noisyPng.byteLength);
+ });
+
+ it("leaves a lossless image note untouched unless conversion is asked for", async () => {
+ const noteId = await createImageNote(noisyPng);
+
+ const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`);
+
+ expect(res.body.compressedCount).toBe(0);
+ expect(res.body.items[0]).toMatchObject({ compressed: false, skipReason: "no-gain", mime: "image/png" });
+ // A skipped image weighs the same on both sides, so the run reports no saving at all.
+ expect(res.body.originalSize).toBe(noisyPng.byteLength);
+ expect(res.body.newSize).toBe(noisyPng.byteLength);
+ expect(res.body.savedSize).toBe(0);
+ expect(readNote(noteId).size).toBe(noisyPng.byteLength);
+ });
+
+ it("visits every image attachment of a text note and reports each one", async () => {
+ const { noteId } = await createTextNote(api);
+ const big = await addAttachment(noteId, "big.png", noisyPng);
+ const small = await addAttachment(noteId, "small.png", smallPng);
+ // Not an image: attachments of other roles are not part of the run at all.
+ await addAttachment(noteId, "notes.txt", new Uint8Array([ 1, 2, 3 ]), { role: "file", mime: "text/plain" });
+
+ const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {
+ body: { convertLossless: true }
+ });
+
+ expect(res.body.items.map((item) => item.entityId).sort()).toEqual([ big, small ].sort());
+ expect(res.body.compressedCount).toBe(1);
+ expect(res.body.skippedCount).toBe(1);
+
+ expect(itemFor(res.body, big)).toMatchObject({ entityType: "attachment", compressed: true, mime: "image/jpeg" });
+ expect(itemFor(res.body, small)).toMatchObject({ compressed: false, skipReason: "no-gain", mime: "image/png" });
+
+ expect(readAttachment(big).mime).toBe("image/jpeg");
+ // The title is deliberately left alone: elsewhere it is a reference, and download and export
+ // filenames already take their extension from the mime.
+ expect(readAttachment(big).title).toBe("big.png");
+ expect(readAttachment(small).size).toBe(smallPng.byteLength);
+ });
+
+ it("reports an empty run for a note holding no images", async () => {
+ const { noteId } = await createTextNote(api);
+
+ const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`);
+
+ expect(res.body).toMatchObject({ items: [], compressedCount: 0, skippedCount: 0, savedSize: 0 });
+ });
+
+ it("does not follow child notes, which may be clones shared with other notes", async () => {
+ const { noteId } = await createTextNote(api);
+ const childId = await createImageNote(noisyPng, noteId);
+
+ const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {
+ body: { convertLossless: true }
+ });
+
+ expect(res.body.items).toHaveLength(0);
+ expect(readNote(childId).size).toBe(noisyPng.byteLength);
+ });
+
+ it("skips the generated picture of a spreadsheet note, which is rebuilt on every save", async () => {
+ const { noteId } = await createTextNote(api);
+ const attachmentId = await addAttachment(noteId, "spreadsheet-export.png", noisyPng);
+ setNoteType(noteId, "spreadsheet", "application/json");
+
+ const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {
+ body: { convertLossless: true }
+ });
+
+ expect(res.body.items[0]).toMatchObject({
+ entityId: attachmentId,
+ compressed: false,
+ skipReason: "generated",
+ // Reported at its real weight even though it was never touched.
+ originalSize: noisyPng.byteLength
+ });
+ expect(readAttachment(attachmentId).mime).toBe("image/png");
+ });
+
+ it("skips a protected image when no protected session is open", async () => {
+ const noteId = await createImageNote(noisyPng);
+ cls.init(() => { becca.getNoteOrThrow(noteId).isProtected = true; });
+
+ const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {
+ body: { convertLossless: true }
+ });
+
+ expect(res.body.items[0]).toMatchObject({ compressed: false, skipReason: "protected", originalSize: 0 });
+
+ cls.init(() => { becca.getNoteOrThrow(noteId).isProtected = false; });
+ });
+
+ it("reports an undecodable image as an error and leaves it alone", async () => {
+ const noteId = await createImageNote(corruptPng);
+
+ const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {
+ body: { convertLossless: true, maxWidthHeight: 100 }
+ });
+
+ expect(res.status).toBe(200);
+ expect(res.body.items[0]).toMatchObject({ compressed: false, skipReason: "error", originalSize: corruptPng.byteLength });
+ expect(readNote(noteId).size).toBe(corruptPng.byteLength);
+ });
+
+ it("carries on past a failing image to the ones after it", async () => {
+ const { noteId } = await createTextNote(api);
+ const broken = await addAttachment(noteId, "broken.png", corruptPng);
+ const good = await addAttachment(noteId, "good.png", noisyPng);
+
+ const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {
+ body: { convertLossless: true }
+ });
+
+ expect(itemFor(res.body, broken).skipReason).toBe("error");
+ expect(itemFor(res.body, good).compressed).toBe(true);
+ });
+});
+
+describe("compression parameters", () => {
+ it("resizes to the requested bound rather than the option's", async () => {
+ const noteId = await createImageNote(noisyPng);
+
+ await api.post(`/api/notes/${noteId}/compress-images`, { body: { maxWidthHeight: 100 } });
+
+ expect(await decodedSize(noteId)).toEqual([ 100, 67 ]);
+ });
+
+ it("falls back to the imageMaxWidthHeight option when no bound is given", async () => {
+ cls.init(() => options.setOption("imageMaxWidthHeight", "150"));
+ const noteId = await createImageNote(noisyPng);
+
+ await api.post(`/api/notes/${noteId}/compress-images`, { body: { convertLossless: true } });
+
+ expect(await decodedSize(noteId)).toEqual([ 150, 100 ]);
+ });
+
+ it("honours the requested quality, and falls back to the imageJpegQuality option without one", async () => {
+ const explicitLow = await compressedSize({ convertLossless: true, quality: 20 });
+ const explicitHigh = await compressedSize({ convertLossless: true, quality: 70 });
+ expect(explicitLow).toBeLessThan(explicitHigh);
+
+ cls.init(() => options.setOption("imageJpegQuality", "20"));
+ expect(await compressedSize({ convertLossless: true })).toBe(explicitLow);
+ });
+
+ it("falls back to the default quality when the stored option is out of range", async () => {
+ cls.init(() => options.setOption("imageJpegQuality", "75"));
+ const at75 = await compressedSize({ convertLossless: true });
+
+ // An option the caller did not choose and cannot fix from here must not fail the request.
+ cls.init(() => options.setOption("imageJpegQuality", "500"));
+ expect(await compressedSize({ convertLossless: true })).toBe(at75);
+ });
+
+ it.each([
+ [ "a fractional maxWidthHeight", { maxWidthHeight: 10.5 } ],
+ [ "a zero maxWidthHeight", { maxWidthHeight: 0 } ],
+ [ "a quality below the minimum", { quality: 5 } ],
+ [ "a quality above the maximum", { quality: 101 } ],
+ [ "a non-integer quality", { quality: 75.5 } ],
+ [ "a non-boolean convertLossless", { convertLossless: "yes" } ]
+ ])("400s on %s", async (_label, body) => {
+ const noteId = await createImageNote(smallPng);
+
+ const res = await api.post(`/api/notes/${noteId}/compress-images`, { body });
+
+ expect(res.status).toBe(400);
+ });
+
+ it("400s on a body that is not an object of options", async () => {
+ const noteId = await createImageNote(smallPng);
+
+ expect((await api.post(`/api/notes/${noteId}/compress-images`, { body: [ 1, 2 ] })).status).toBe(400);
+ expect((await api.post(`/api/notes/${noteId}/compress-images`, { body: "convertLossless" })).status).toBe(400);
+ });
+
+ it("treats a missing body as a request for the defaults", async () => {
+ const noteId = await createImageNote(noisyPng);
+
+ const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`);
+
+ expect(res.status).toBe(200);
+ // Defaults: no conversion, so a PNG within the bound is left exactly as it was.
+ expect(res.body.items[0]).toMatchObject({ compressed: false, mime: "image/png" });
+ });
+});
+
+describe("compress one attachment (POST /api/attachments/:attachmentId/compress-image)", () => {
+ it("404s for an attachment that does not exist", async () => {
+ const res = await api.post("/api/attachments/missingAtt123/compress-image");
+
+ expect(res.status).toBe(404);
+ });
+
+ it("400s for an attachment that is not an image", async () => {
+ const { noteId } = await createTextNote(api);
+ const attachmentId = await addAttachment(noteId, "notes.txt", new Uint8Array([ 1, 2 ]), { role: "file", mime: "text/plain" });
+
+ const res = await api.post(`/api/attachments/${attachmentId}/compress-image`);
+
+ expect(res.status).toBe(400);
+ });
+
+ it("compresses just that attachment, leaving its siblings alone", async () => {
+ const { noteId } = await createTextNote(api);
+ const target = await addAttachment(noteId, "target.png", noisyPng);
+ const sibling = await addAttachment(noteId, "sibling.png", noisyPng);
+
+ const res = await api.post<ImageCompressionResponse>(`/api/attachments/${target}/compress-image`, {
+ body: { convertLossless: true }
+ });
+
+ expect(res.body.items).toHaveLength(1);
+ expect(res.body.items[0]).toMatchObject({ entityType: "attachment", entityId: target, compressed: true });
+ expect(readAttachment(target).mime).toBe("image/jpeg");
+ expect(readAttachment(sibling).size).toBe(noisyPng.byteLength);
+ });
+
+ it("still refuses a generated picture when it is targeted directly", async () => {
+ const { noteId } = await createTextNote(api);
+ const attachmentId = await addAttachment(noteId, "spreadsheet-export.png", noisyPng);
+ setNoteType(noteId, "spreadsheet", "application/json");
+
+ const res = await api.post<ImageCompressionResponse>(`/api/attachments/${attachmentId}/compress-image`, {
+ body: { convertLossless: true }
+ });
+
+ expect(res.body.items[0]).toMatchObject({ compressed: false, skipReason: "generated" });
+ });
+});
+
+/** Creates a real image note holding the given bytes and returns its noteId. */
+async function createImageNote(content: Uint8Array, parentNoteId = "root"): Promise<string> {
+ const { noteId } = await createTextNote(api, { parentNoteId });
+
+ cls.init(() => getSql().transactional(() => {
+ const note = becca.getNoteOrThrow(noteId);
+ note.type = "image";
+ note.mime = "image/png";
+ note.save();
+ note.setContent(content, { forceSave: true });
+ }));
+
+ return noteId;
+}
+
+async function addAttachment(
+ noteId: string,
+ title: string,
+ content: Uint8Array,
+ { role = "image", mime = "image/png" } = {}
+): Promise<string> {
+ return cls.init(() => getSql().transactional(() => {
+ const attachment = becca.getNoteOrThrow(noteId).saveAttachment({ role, mime, title, content }, "title");
+ return attachment.attachmentId ?? "";
+ }));
+}
+
+function setNoteType(noteId: string, type: string, mime: string) {
+ cls.init(() => getSql().transactional(() => {
+ const note = becca.getNoteOrThrow(noteId);
+ note.type = type as never;
+ note.mime = mime;
+ note.save();
+ }));
+}
+
+function readNote(noteId: string): { mime: string; size: number } {
+ return cls.init(() => {
+ const note = becca.getNoteOrThrow(noteId);
+ return { mime: note.mime, size: note.getContent().length };
+ });
+}
+
+function readAttachment(attachmentId: string): { mime: string; title: string; size: number } {
+ return cls.init(() => {
+ const attachment = becca.getAttachmentOrThrow(attachmentId);
+ return { mime: attachment.mime, title: attachment.title, size: attachment.getContent().length };
+ });
+}
+
+function itemFor(response: ImageCompressionResponse, entityId: string) {
+ const item = response.items.find((candidate) => candidate.entityId === entityId);
+
+ if (!item) {
+ throw new Error(`No item reported for '${entityId}'.`);
+ }
+
+ return item;
+}
+
+/** Compresses a fresh copy of the noisy PNG and returns how many bytes it ended up at. */
+async function compressedSize(body: Record<string, unknown>): Promise<number> {
+ const noteId = await createImageNote(noisyPng);
+ const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, { body });
+
+ if (res.body.compressedCount !== 1) {
+ throw new Error(`Expected ${JSON.stringify(body)} to compress; got ${JSON.stringify(res.body.items)}`);
+ }
+
+ return res.body.newSize;
+}
+
+async function decodedSize(noteId: string): Promise<[number, number]> {
+ const content = cls.init(() => becca.getNoteOrThrow(noteId).getContent());
+ const decoded = await Jimp.read(Buffer.from(content as Uint8Array));
+
+ return [ decoded.bitmap.width, decoded.bitmap.height ];
+}
diff --git a/apps/server/src/services/image_provider.spec.ts b/apps/server/src/services/image_provider.spec.ts
index 3eb037afe9..a5414cde06 100644
--- a/apps/server/src/services/image_provider.spec.ts
+++ b/apps/server/src/services/image_provider.spec.ts
@@ -1,4 +1,4 @@
-import { cls, options } from '@triliumnext/core';
+import { cls, type ImageCompressionRequest, options } from '@triliumnext/core';
import { Jimp } from 'jimp';
import { afterEach, beforeAll, describe, expect, it } from 'vitest';
@@ -22,6 +22,9 @@ let tallPng: Uint8Array; // 200x600 -> resized by height
let smallPng: Uint8Array; // 8x8 -> within bounds, jpeg ends up larger
let noisyPng: Uint8Array; // large noisy image where jpeg compression helps
let corruptPng: Uint8Array; // valid PNG signature but unreadable by jimp
+let transparentPng: Uint8Array; // 600x400 noisy, every pixel half-transparent
+let noisyJpeg: Uint8Array; // 600x400 noisy jpeg stored at high quality
+let tinyJpeg: Uint8Array; // 8x8 jpeg that cannot get any smaller
const svgBuffer = new TextEncoder().encode('<svg xmlns="http://www.w3.org/2000/svg"></svg>');
const garbageBuffer = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
const staticGif = Uint8Array.from(
@@ -35,20 +38,24 @@ const animatedGif = Uint8Array.from(
)
);
-async function makePng(width: number, height: number, noisy = false): Promise<Uint8Array> {
- const image = new Jimp({ width, height, color: 0x3366ccff });
+function makeImage(width: number, height: number, { noisy = false, alpha = 0xff } = {}): InstanceType<typeof Jimp> {
+ const image = new Jimp({ width, height, color: (0x3366cc00 | alpha) >>> 0 });
if (noisy) {
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
const r = (x * 31 + y * 17) % 256;
const g = (x * 13 + y * 7) % 256;
const b = (x * 5 + y * 23) % 256;
- const color = (((r << 24) | (g << 16) | (b << 8) | 0xff) >>> 0);
+ const color = (((r << 24) | (g << 16) | (b << 8) | alpha) >>> 0);
image.setPixelColor(color, x, y);
}
}
}
- return new Uint8Array(await image.getBuffer('image/png'));
+ return image;
+}
+
+async function makePng(width: number, height: number, noisy = false): Promise<Uint8Array> {
+ return new Uint8Array(await makeImage(width, height, { noisy }).getBuffer('image/png'));
}
beforeAll(async () => {
@@ -59,6 +66,13 @@ beforeAll(async () => {
corruptPng = new Uint8Array(
Buffer.concat([Buffer.from(valid.slice(0, 50)), Buffer.alloc(valid.length, 0xab)])
);
+ transparentPng = new Uint8Array(
+ await makeImage(600, 400, { noisy: true, alpha: 0x80 }).getBuffer('image/png')
+ );
+ noisyJpeg = new Uint8Array(
+ await makeImage(600, 400, { noisy: true }).getBuffer('image/jpeg', { quality: 100 })
+ );
+ tinyJpeg = new Uint8Array(await makeImage(8, 8).getBuffer('image/jpeg', { quality: 10 }));
}, 30000);
afterEach(() => {
@@ -221,6 +235,156 @@ describe('serverImageProvider.processImage', () => {
});
});
+describe('serverImageProvider.compressImage', () => {
+ /** Every parameter is explicit, so nothing here depends on the stored options. */
+ function request(overrides: Partial<ImageCompressionRequest> = {}): ImageCompressionRequest {
+ return { maxWidthHeight: 2000, quality: 75, convertLossless: false, ...overrides };
+ }
+
+ it.each([
+ ['an SVG', () => svgBuffer],
+ ['a GIF', () => staticGif],
+ ['an animated GIF', () => animatedGif],
+ ['an unrecognisable buffer', () => garbageBuffer]
+ ])('leaves %s alone as an unsupported format', async (_label, getBuffer) => {
+ const outcome = await serverImageProvider.compressImage(getBuffer(), request());
+
+ expect(outcome).toEqual({ compressed: false, reason: 'unsupported-format' });
+ });
+
+ it('ignores the compressImages option, which only governs automatic shrinking', async () => {
+ setOptions({ compressImages: 'false' });
+
+ const outcome = await serverImageProvider.compressImage(noisyPng, request({ maxWidthHeight: 100 }));
+
+ expect(outcome.compressed).toBe(true);
+ });
+
+ describe('lossless sources', () => {
+ it('re-encodes an opaque PNG as JPEG once conversion is allowed', async () => {
+ const outcome = await serverImageProvider.compressImage(noisyPng, request({ convertLossless: true }));
+
+ expect(outcome).toMatchObject({ compressed: true, format: { ext: 'jpg', mime: 'image/jpeg' } });
+ if (!outcome.compressed) return;
+ expect(outcome.buffer.byteLength).toBeLessThan(noisyPng.byteLength);
+
+ // Still 600x400: converting is worthwhile on its own, without any resizing.
+ const decoded = await Jimp.read(Buffer.from(outcome.buffer));
+ expect([decoded.bitmap.width, decoded.bitmap.height]).toEqual([600, 400]);
+ });
+
+ it('never re-encodes a PNG that is already within bounds when conversion is off', async () => {
+ const outcome = await serverImageProvider.compressImage(noisyPng, request());
+
+ expect(outcome).toEqual({ compressed: false, reason: 'no-gain' });
+ });
+
+ it('scales an oversized PNG down but keeps it a PNG when conversion is off', async () => {
+ const outcome = await serverImageProvider.compressImage(noisyPng, request({ maxWidthHeight: 100 }));
+
+ expect(outcome).toMatchObject({ compressed: true, format: { ext: 'png', mime: 'image/png' } });
+ if (!outcome.compressed) return;
+
+ const decoded = await Jimp.read(Buffer.from(outcome.buffer));
+ expect([decoded.bitmap.width, decoded.bitmap.height]).toEqual([100, 67]);
+ });
+ });
+
+ describe('transparency', () => {
+ it('refuses to convert a transparent PNG, which JPEG cannot represent', async () => {
+ const outcome = await serverImageProvider.compressImage(transparentPng, request({ convertLossless: true }));
+
+ expect(outcome).toEqual({ compressed: false, reason: 'transparent' });
+ });
+
+ it('still scales a transparent PNG down, keeping both the format and the alpha channel', async () => {
+ const outcome = await serverImageProvider.compressImage(
+ transparentPng,
+ request({ maxWidthHeight: 100, convertLossless: true })
+ );
+
+ expect(outcome).toMatchObject({ compressed: true, format: { ext: 'png', mime: 'image/png' } });
+ if (!outcome.compressed) return;
+
+ // The point of the refusal above: the transparency has to survive the resize intact.
+ const decoded = await Jimp.read(Buffer.from(outcome.buffer));
+ expect(decoded.bitmap.width).toBe(100);
+ expect(decoded.bitmap.data.some((byte, i) => i % 4 === 3 && byte !== 255)).toBe(true);
+ });
+
+ it('converts a PNG whose alpha channel is fully opaque', async () => {
+ // Detection reads the decoded pixels, so an alpha channel that happens to be all-255
+ // is correctly treated as no transparency at all rather than assumed dangerous.
+ const opaqueWithAlpha = new Uint8Array(
+ await makeImage(600, 400, { noisy: true, alpha: 0xff }).getBuffer('image/png')
+ );
+
+ const outcome = await serverImageProvider.compressImage(opaqueWithAlpha, request({ convertLossless: true }));
+
+ expect(outcome).toMatchObject({ compressed: true, format: { ext: 'jpg', mime: 'image/jpeg' } });
+ });
+ });
+
+ describe('lossy sources', () => {
+ it('recompresses a JPEG at the requested quality without resizing it', async () => {
+ const outcome = await serverImageProvider.compressImage(noisyJpeg, request({ quality: 40 }));
+
+ expect(outcome).toMatchObject({ compressed: true, format: { ext: 'jpg', mime: 'image/jpeg' } });
+ if (!outcome.compressed) return;
+ expect(outcome.buffer.byteLength).toBeLessThan(noisyJpeg.byteLength);
+ });
+
+ it('produces a smaller file at a lower quality', async () => {
+ const at80 = await serverImageProvider.compressImage(noisyJpeg, request({ quality: 80 }));
+ const at20 = await serverImageProvider.compressImage(noisyJpeg, request({ quality: 20 }));
+
+ if (!at80.compressed || !at20.compressed) throw new Error('expected both to compress');
+ expect(at20.buffer.byteLength).toBeLessThan(at80.buffer.byteLength);
+ });
+
+ it('keeps the original when recompressing would not save anything', async () => {
+ const outcome = await serverImageProvider.compressImage(tinyJpeg, request());
+
+ expect(outcome).toEqual({ compressed: false, reason: 'no-gain' });
+ });
+ });
+
+ describe('resizing', () => {
+ it('scales a wide image by its width', async () => {
+ const outcome = await serverImageProvider.compressImage(noisyJpeg, request({ maxWidthHeight: 120 }));
+
+ if (!outcome.compressed) throw new Error('expected compression');
+ const decoded = await Jimp.read(Buffer.from(outcome.buffer));
+ expect([decoded.bitmap.width, decoded.bitmap.height]).toEqual([120, 80]);
+ });
+
+ it('scales a tall image by its height', async () => {
+ const outcome = await serverImageProvider.compressImage(
+ tallPng,
+ request({ maxWidthHeight: 120, convertLossless: true })
+ );
+
+ if (!outcome.compressed) throw new Error('expected compression');
+ const decoded = await Jimp.read(Buffer.from(outcome.buffer));
+ expect([decoded.bitmap.width, decoded.bitmap.height]).toEqual([40, 120]);
+ });
+
+ it('leaves an image already within bounds at its size', async () => {
+ const outcome = await serverImageProvider.compressImage(noisyJpeg, request({ maxWidthHeight: 600 }));
+
+ if (!outcome.compressed) throw new Error('expected compression');
+ const decoded = await Jimp.read(Buffer.from(outcome.buffer));
+ expect([decoded.bitmap.width, decoded.bitmap.height]).toEqual([600, 400]);
+ });
+ });
+
+ it('propagates a decode failure rather than reporting a bogus result', async () => {
+ // corruptPng passes format detection as PNG but Jimp cannot read it. The caller turns this
+ // into a logged, per-image "error" skip; swallowing it here would hide the failure instead.
+ await expect(serverImageProvider.compressImage(corruptPng, request({ maxWidthHeight: 100 }))).rejects.toThrow();
+ });
+});
+
/**
* Builds a noisy `width`x`height` JPEG (stored at those dimensions) carrying an EXIF Orientation
* tag. Orientation 6 ("rotate 90 CW") means a 600x400 stored image should be displayed as 400x600
diff --git a/apps/server/src/services/image_provider.ts b/apps/server/src/services/image_provider.ts
index d2d267a64c..0705dab984 100644
--- a/apps/server/src/services/image_provider.ts
+++ b/apps/server/src/services/image_provider.ts
@@ -3,14 +3,18 @@
* Uses JIMP for image processing with full compression support.
*/
+import { getLog, options as optionService } from "@triliumnext/core";
+import type { ImageCompressionOutcome, ImageCompressionRequest, ImageFormat, ImageProvider, ProcessedImage } from "@triliumnext/core/src/services/image_provider.js";
import imageType from "image-type";
import isAnimated from "is-animated";
import isSvg from "is-svg";
import { Jimp } from "jimp";
-import { options as optionService } from "@triliumnext/core";
-import type { ImageProvider, ImageFormat, ProcessedImage } from "@triliumnext/core/src/services/image_provider.js";
-import { getLog } from "@triliumnext/core";
+const JPEG_FORMAT: ImageFormat = { ext: "jpg", mime: "image/jpeg" };
+const PNG_FORMAT: ImageFormat = { ext: "png", mime: "image/png" };
+
+/** The only formats JIMP can both decode and re-encode here; everything else is left untouched. */
+const COMPRESSIBLE_EXTENSIONS = new Set([ "jpg", "png" ]);
async function getImageTypeFromBuffer(buffer: Uint8Array): Promise<ImageFormat | null> {
// Check for SVG first (text-based)
@@ -118,5 +122,78 @@ export const serverImageProvider: ImageProvider = {
}
return { buffer: finalBuffer, format };
+ },
+
+ async compressImage(buffer: Uint8Array, request: ImageCompressionRequest): Promise<ImageCompressionOutcome> {
+ const format = await getImageTypeFromBuffer(buffer);
+
+ if (!format || !COMPRESSIBLE_EXTENSIONS.has(format.ext)) {
+ return { compressed: false, reason: "unsupported-format" };
+ }
+
+ /* v8 ignore start -- the same rare defensive guard as in processImage above: spec-compliant
+ animated images already fail the format gate (file-type reports animated PNG as "apng"
+ and animated GIF/WebP as gif/webp). Only a pathological PNG with 512+ chunks before its
+ acTL chunk reaches here, and recompressing it would keep the first frame alone. */
+ if (isAnimated(Buffer.from(buffer))) {
+ return { compressed: false, reason: "animated" };
+ }
+ /* v8 ignore stop */
+
+ const start = Date.now();
+ const image = await Jimp.read(Buffer.from(buffer));
+ const { width, height } = image.bitmap;
+ const needsResize = Math.max(width, height) > request.maxWidthHeight;
+ const isLossless = format.ext === "png";
+
+ // JPEG has no alpha channel, so a transparent PNG would come back with its transparency
+ // filled in — the one conversion that visibly damages an image rather than degrading it.
+ // The check reads the decoded pixels, so it is exact rather than a guess from the header.
+ const toJpeg = !isLossless || (request.convertLossless && !hasTransparency(image));
+
+ if (!toJpeg && !needsResize) {
+ // Nothing left to do: re-encoding a PNG at its own size is lossless and pointless.
+ return { compressed: false, reason: isLossless && request.convertLossless ? "transparent" : "no-gain" };
+ }
+
+ if (needsResize) {
+ if (width >= height) {
+ image.resize({ w: request.maxWidthHeight });
+ } else {
+ image.resize({ h: request.maxWidthHeight });
+ }
+ }
+
+ let result: Uint8Array;
+
+ if (toJpeg) {
+ // Whatever transparency survives here is known to be absent or deliberately discarded.
+ image.background = 0xffffffff;
+ result = await image.getBuffer("image/jpeg", { quality: request.quality });
+ } else {
+ result = await image.getBuffer("image/png");
+ }
+
+ getLog().info(`Compressing image of ${buffer.byteLength} bytes took ${Date.now() - start}ms`);
+
+ if (result.byteLength >= buffer.byteLength) {
+ // A small or already well-compressed image can grow; the original stays.
+ return { compressed: false, reason: "no-gain" };
+ }
+
+ return { compressed: true, buffer: result, format: toJpeg ? JPEG_FORMAT : PNG_FORMAT };
}
};
+
+/** True when any pixel is less than fully opaque, read off the decoded RGBA bitmap. */
+function hasTransparency(image: Awaited<ReturnType<typeof Jimp.read>>): boolean {
+ const { data } = image.bitmap;
+
+ for (let i = 3; i < data.length; i += 4) {
+ if (data[i] !== 255) {
+ return true;
+ }
+ }
+
+ return false;
+}
diff --git a/apps/standalone/src/services/image_provider.spec.ts b/apps/standalone/src/services/image_provider.spec.ts
index a772a6dfc8..2b86441299 100644
--- a/apps/standalone/src/services/image_provider.spec.ts
+++ b/apps/standalone/src/services/image_provider.spec.ts
@@ -76,3 +76,15 @@ describe("standaloneImageProvider.processImage", () => {
expect(result.format).toEqual({ ext: "dat", mime: "application/octet-stream" });
});
});
+
+describe("standaloneImageProvider.compressImage", () => {
+ it("answers that this runtime cannot compress, rather than failing the request", async () => {
+ // There is no decoder here, so every image an on-demand compression run visits comes back
+ // untouched with the reason attached — the caller reports it instead of erroring out.
+ const buffer = withMagic([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
+
+ await expect(
+ standaloneImageProvider.compressImage(buffer, { maxWidthHeight: 100, quality: 75, convertLossless: true })
+ ).resolves.toEqual({ compressed: false, reason: "unsupported-platform" });
+ });
+});
diff --git a/apps/standalone/src/services/image_provider.ts b/apps/standalone/src/services/image_provider.ts
index d5c2ca949e..2fc3f1b5f8 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 { ImageProvider, ImageFormat, ProcessedImage } from "@triliumnext/core";
+import type { ImageCompressionOutcome, ImageFormat, ImageProvider, ProcessedImage } from "@triliumnext/core";
/**
* Detect image type from buffer using magic bytes.
@@ -92,5 +92,11 @@ export const standaloneImageProvider: ImageProvider = {
buffer,
format
};
+ },
+
+ async compressImage(): Promise<ImageCompressionOutcome> {
+ // No decoder here, so there is nothing to recompress with — the request is answered rather
+ // than refused, and the caller reports the images as untouched along with the reason.
+ return { compressed: false, reason: "unsupported-platform" };
}
};
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.ts
index 58552359f5..f696aa49b0 100644
--- a/packages/commons/src/lib/server_api.ts
+++ b/packages/commons/src/lib/server_api.ts
@@ -283,6 +283,82 @@ export interface SubtreeSizeResponse {
subTreeSize: number;
}
+/**
+ * How far an on-demand image compression run should go. Every field is optional, and what is left
+ * out falls back to the corresponding option — so an empty request compresses exactly the way the
+ * automatic import-time shrinking would, only without needing that shrinking to be enabled.
+ *
+ * Unlike the `compressImages` option, this is always a deliberate act by the user on one note or
+ * one image, so it runs whether or not automatic compression is switched on.
+ */
+export interface ImageCompressionOptions {
+ /**
+ * Longest edge, in pixels: an image larger than this is scaled down to fit, one smaller is left
+ * at its size. Omitted, it falls back to the `imageMaxWidthHeight` option.
+ */
+ maxWidthHeight?: number;
+ /**
+ * JPEG quality, 10 to 100. Omitted, it falls back to the `imageJpegQuality` option (75 by
+ * default). Only reaches images actually encoded as JPEG — see {@link convertLossless}.
+ */
+ quality?: number;
+ /**
+ * Whether a lossless source (PNG) may be re-encoded as JPEG. Off by default, since that trades
+ * away quality permanently; with it off a PNG is only ever scaled down, never re-encoded.
+ */
+ convertLossless?: boolean;
+}
+
+/**
+ * Why a particular image was left exactly as it was. Every image the run visited is reported, so
+ * "nothing happened" always comes with the reason it didn't.
+ */
+export type ImageCompressionSkipReason =
+ /** Not a format that can be recompressed — SVG, an unrecognised buffer, GIF, WebP, BMP … */
+ | "unsupported-format"
+ /** Animated (APNG, animated GIF/WebP): recompressing would flatten it to a single frame. */
+ | "animated"
+ /** A PNG carrying transparency, which JPEG cannot represent, and no resizing to do besides. */
+ | "transparent"
+ /** The rendered picture of a canvas/mermaid/mind map/spreadsheet note, regenerated on save. */
+ | "generated"
+ /** Protected, with no protected session open to decrypt it. */
+ | "protected"
+ /** Compressing produced nothing smaller, so the original was kept. */
+ | "no-gain"
+ /** This build has no image compression at all (the standalone/WASM runtime). */
+ | "unsupported-platform"
+ /** Compression failed; the original was kept and the failure logged. */
+ | "error";
+
+/** One image visited by a compression run, whether or not it ended up compressed. */
+export interface ImageCompressionItem {
+ entityType: "note" | "attachment";
+ /** The `noteId` of an image note, or the `attachmentId` of an image attachment. */
+ entityId: string;
+ title: string;
+ /** The mime after the run: the new one when compressed, the untouched one otherwise. */
+ mime: string;
+ originalSize: number;
+ /** Equal to {@link originalSize} whenever the image was left alone. */
+ newSize: number;
+ compressed: boolean;
+ /** Present exactly when {@link compressed} is false. */
+ skipReason?: ImageCompressionSkipReason;
+}
+
+export interface ImageCompressionResponse {
+ /** Every image the run visited, skipped ones included, in the order they were visited. */
+ items: ImageCompressionItem[];
+ compressedCount: number;
+ skippedCount: number;
+ /** Summed over {@link items}, so skipped images weigh the same on both sides. */
+ originalSize: number;
+ newSize: number;
+ /** `originalSize - newSize`; never negative, an image is only replaced when it got smaller. */
+ savedSize: number;
+}
+
/**
* The size components of a single note. Revisions are always reported separately so a client can
* include or exclude them without another request.
diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.ts
index 91459f4938..ac5cfdacc2 100644
--- a/packages/trilium-core/src/index.ts
+++ b/packages/trilium-core/src/index.ts
@@ -107,7 +107,8 @@ export { default as sync_mutex } from "./services/sync_mutex";
export { default as setup } from "./services/setup";
export { getPlatform, type PlatformProvider } from "./services/platform";
export { InAppHelpProvider } from "./services/in_app_help";
-export { type ImageProvider, type ImageFormat, type ProcessedImage, getImageProvider } from "./services/image_provider";
+export { type ImageProvider, type ImageFormat, type ImageCompressionOutcome, type ImageCompressionRequest, type ProcessedImage, getImageProvider } from "./services/image_provider";
+export { default as imageCompressionService } from "./services/image_compression";
export { type CoreConfig, initConfig, getConfig } from "./services/config";
export { default as imageService } from "./services/image";
export { t } from "i18next";
diff --git a/packages/trilium-core/src/routes/api/image.ts b/packages/trilium-core/src/routes/api/image.ts
index 0b07a91fb1..40c531008f 100644
--- a/packages/trilium-core/src/routes/api/image.ts
+++ b/packages/trilium-core/src/routes/api/image.ts
@@ -1,4 +1,4 @@
-import { NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";
+import { type ImageCompressionOptions, NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";
import type { Request, Response } from "express";
import type { File } from "../../services/import/common.js";
@@ -7,7 +7,9 @@ type FileRequest<P> = Omit<Request<P>, "file"> & { file?: File };
import becca from "../../becca/becca.js";
import type BNote from "../../becca/entities/bnote.js";
import type BRevision from "../../becca/entities/brevision.js";
+import { ValidationError } from "../../errors.js";
import imageService from "../../services/image.js";
+import imageCompressionService from "../../services/image_compression.js";
import { sanitizeSvg, SVG_CONTENT_SECURITY_POLICY } from "../../services/utils/index.js";
import { unwrapStringOrBuffer } from "../../services/utils/binary.js";
@@ -139,13 +141,42 @@ function updateImage(req: FileRequest<{ noteId: string }>) {
return { uploaded: true };
}
+function compressNoteImages(req: Request<{ noteId: string }>) {
+ return imageCompressionService.compressNoteImages(req.params.noteId, readCompressionOptions(req));
+}
+
+function compressAttachmentImage(req: Request<{ attachmentId: string }>) {
+ return imageCompressionService.compressAttachmentImage(req.params.attachmentId, readCompressionOptions(req));
+}
+
export default {
returnImageFromNote,
returnImageFromRevision,
returnAttachedImage,
- updateImage
+ updateImage,
+ compressNoteImages,
+ compressAttachmentImage
};
+/**
+ * The body is optional — sending none asks for the defaults — but anything that is sent has to be
+ * an object, so a stray array or string fails here rather than being silently read as "defaults".
+ * The individual fields are validated by the service, which owns their bounds and fallbacks.
+ */
+function readCompressionOptions(req: Request): ImageCompressionOptions {
+ const { body } = req;
+
+ if (body === undefined || body === null) {
+ return {};
+ }
+
+ if (typeof body !== "object" || Array.isArray(body)) {
+ throw new ValidationError("The request body must be an object of compression options.");
+ }
+
+ return body as ImageCompressionOptions;
+}
+
function sendSanitizedSvg(res: Response, content: string | Uint8Array) {
const svgString = unwrapStringOrBuffer(content);
res.set("Content-Security-Policy", SVG_CONTENT_SECURITY_POLICY);
diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.ts
index 371f8ebf64..3de583cb98 100644
--- a/packages/trilium-core/src/routes/index.ts
+++ b/packages/trilium-core/src/routes/index.ts
@@ -131,6 +131,10 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRout
route(GET, "/api/attachments/:attachmentId/image/:filename", [checkApiAuthOrElectron], imageRoute.returnAttachedImage);
route(GET, "/api/images/:noteId/:filename", [checkApiAuthOrElectron], imageRoute.returnImageFromNote);
route(PUT, "/api/images/:noteId", [checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], imageRoute.updateImage, apiResultHandler);
+ // Recompressing decodes and re-encodes each image, so these run outside a transaction and open
+ // one per image written instead of holding a single one across the whole (asynchronous) run.
+ asyncApiRoute(PST, "/api/notes/:noteId/compress-images", imageRoute.compressNoteImages);
+ asyncApiRoute(PST, "/api/attachments/:attachmentId/compress-image", imageRoute.compressAttachmentImage);
route(PST, "/api/notes/:noteId/attachments/upload", [checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], attachmentsApiRoute.uploadAttachment, apiResultHandler);
// group of the services below are meant to be executed from the outside
diff --git a/packages/trilium-core/src/services/image_compression.ts b/packages/trilium-core/src/services/image_compression.ts
new file mode 100644
index 0000000000..047f265edc
--- /dev/null
+++ b/packages/trilium-core/src/services/image_compression.ts
@@ -0,0 +1,269 @@
+/**
+ * On-demand image compression: shrinks the images a note already holds, when the user asks for it.
+ *
+ * The `compressImages` option shrinks images as they come in, and is usually left off because it
+ * costs quality on every image regardless. This service is the other half of that trade: nothing
+ * happens automatically, but a single note (or a single image) whose attachments have grown out of
+ * hand can be shrunk deliberately, accepting the quality loss for that one note alone. It therefore
+ * runs whether or not the option is enabled.
+ *
+ * What it decides is *which* images to visit and what to write back; how a single image is actually
+ * recompressed belongs to the platform's {@link ImageProvider}.
+ */
+
+import { getImageAttachmentTitle, type ImageCompressionItem, type ImageCompressionOptions, type ImageCompressionResponse, type ImageCompressionSkipReason } from "@triliumnext/commons";
+
+import becca from "../becca/becca.js";
+import type BAttachment from "../becca/entities/battachment.js";
+import type BNote from "../becca/entities/bnote.js";
+import { NotFoundError, ValidationError } from "../errors.js";
+import { getImageProvider, type ImageCompressionRequest } from "./image_provider.js";
+import { getLog } from "./log.js";
+import optionService from "./options.js";
+import { getSql } from "./sql/index.js";
+import { wrapStringOrBuffer } from "./utils/binary.js";
+
+/** Quality bounds shared with the automatic shrinking, so the two cannot drift apart. */
+const MIN_QUALITY = 10;
+const MAX_QUALITY = 100;
+const DEFAULT_QUALITY = 75;
+/** A one-pixel bound is pointless but harmless; anything below it cannot be resized to. */
+const MIN_MAX_WIDTH_HEIGHT = 1;
+
+/** Compresses every image the given note holds: an image note's own content, or its attachments. */
+export async function compressNoteImages(noteId: string, options?: ImageCompressionOptions): Promise<ImageCompressionResponse> {
+ const note = becca.getNote(noteId);
+
+ if (!note) {
+ throw new NotFoundError(`Note '${noteId}' was not found.`);
+ }
+
+ return compressTargets(collectNoteTargets(note), resolveCompressionRequest(options));
+}
+
+/** Compresses one image attachment, under exactly the rules a whole-note run would apply to it. */
+export async function compressAttachmentImage(attachmentId: string, options?: ImageCompressionOptions): Promise<ImageCompressionResponse> {
+ const attachment = becca.getAttachment(attachmentId);
+
+ if (!attachment) {
+ throw new NotFoundError(`Attachment '${attachmentId}' was not found.`);
+ }
+
+ if (attachment.role !== "image") {
+ throw new ValidationError(`Attachment '${attachmentId}' has role '${attachment.role}', but 'image' was expected.`);
+ }
+
+ return compressTargets([ attachmentTarget(attachment) ], resolveCompressionRequest(options));
+}
+
+/**
+ * Fills in what the request left out and rejects what it got wrong, so a provider always receives
+ * complete, sane parameters. An out-of-range stored option falls back to the default rather than
+ * failing the request — the caller did not choose that value and cannot fix it from here.
+ */
+export function resolveCompressionRequest(options: ImageCompressionOptions = {}): ImageCompressionRequest {
+ const { maxWidthHeight, quality, convertLossless } = options;
+
+ if (maxWidthHeight !== undefined && (!Number.isInteger(maxWidthHeight) || maxWidthHeight < MIN_MAX_WIDTH_HEIGHT)) {
+ throw new ValidationError(`maxWidthHeight must be an integer of ${MIN_MAX_WIDTH_HEIGHT} or above.`);
+ }
+
+ if (quality !== undefined && (!Number.isInteger(quality) || quality < MIN_QUALITY || quality > MAX_QUALITY)) {
+ throw new ValidationError(`quality must be an integer between ${MIN_QUALITY} and ${MAX_QUALITY}.`);
+ }
+
+ if (convertLossless !== undefined && typeof convertLossless !== "boolean") {
+ throw new ValidationError("convertLossless must be a boolean.");
+ }
+
+ return {
+ maxWidthHeight: maxWidthHeight ?? optionService.getOptionInt("imageMaxWidthHeight"),
+ quality: quality ?? defaultQuality(),
+ convertLossless: convertLossless ?? false
+ };
+}
+
+function defaultQuality(): number {
+ const configured = optionService.getOptionInt("imageJpegQuality", 0);
+
+ return configured >= MIN_QUALITY && configured <= MAX_QUALITY ? configured : DEFAULT_QUALITY;
+}
+
+/**
+ * One image the run can act on, hiding whether it lives in a note's content or in an attachment.
+ *
+ * Neither kind is renamed when its format changes: an attachment's title is a reference elsewhere
+ * (a canvas addresses its images by the Excalidraw file id stored as the title), and download and
+ * export filenames already derive their extension from the mime when the title disagrees.
+ */
+interface CompressionTarget {
+ entityType: "note" | "attachment";
+ entityId: string;
+ title: string;
+ mime: string;
+ /** Set when the target must be left alone for a reason known before reading its content. */
+ skip?: ImageCompressionSkipReason;
+ getContent(): Uint8Array;
+ save(buffer: Uint8Array, mime: string): void;
+}
+
+/**
+ * The images a note holds. An image note *is* its image, so it stands alone; for anything else the
+ * images are the attachments it owns — which is where a text note's pictures live, and where the
+ * weight the user is trying to shed actually sits.
+ *
+ * Child notes are deliberately not followed: a child can be a clone shared with other notes, and
+ * shrinking a note should not silently degrade an image somewhere else.
+ */
+function collectNoteTargets(note: BNote): CompressionTarget[] {
+ if (note.type === "image") {
+ return [ noteTarget(note) ];
+ }
+
+ return note.getAttachmentsByRole("image").map((attachment) => attachmentTarget(attachment));
+}
+
+function noteTarget(note: BNote): CompressionTarget {
+ return {
+ entityType: "note",
+ entityId: note.noteId,
+ title: note.title,
+ mime: note.mime,
+ skip: note.isContentAvailable() ? undefined : "protected",
+ getContent: () => wrapStringOrBuffer(note.getContent()),
+ save(buffer, mime) {
+ note.mime = mime;
+ note.save();
+ note.setContent(buffer, { forceSave: true });
+ }
+ };
+}
+
+function attachmentTarget(attachment: BAttachment): CompressionTarget {
+ return {
+ entityType: "attachment",
+ entityId: attachment.attachmentId ?? "",
+ title: attachment.title,
+ mime: attachment.mime,
+ skip: resolveAttachmentSkip(attachment),
+ getContent: () => wrapStringOrBuffer(attachment.getContent()),
+ save(buffer, mime) {
+ attachment.mime = mime;
+ attachment.setContent(buffer, { forceSave: true });
+ }
+ };
+}
+
+/**
+ * A canvas, mermaid, mind map or spreadsheet note carries its rendered picture in an attachment of
+ * a fixed title. Those are regenerated whenever the note is saved, so compressing one buys nothing
+ * and lasts until the next save; worse, the route serving the spreadsheet's picture declares it
+ * `image/png` unconditionally, so converting it to JPEG would serve bytes under the wrong type.
+ */
+function resolveAttachmentSkip(attachment: BAttachment): ImageCompressionSkipReason | undefined {
+ if (!attachment.isContentAvailable()) {
+ return "protected";
+ }
+
+ const ownerNote = attachment.getNote();
+
+ if (ownerNote && attachment.title === getImageAttachmentTitle(ownerNote.type)) {
+ return "generated";
+ }
+
+ return undefined;
+}
+
+async function compressTargets(targets: CompressionTarget[], request: ImageCompressionRequest): Promise<ImageCompressionResponse> {
+ const items: ImageCompressionItem[] = [];
+
+ for (const target of targets) {
+ items.push(await compressTarget(target, request));
+ }
+
+ return summarize(items);
+}
+
+async function compressTarget(target: CompressionTarget, request: ImageCompressionRequest): Promise<ImageCompressionItem> {
+ const skipped = (originalSize: number, skipReason: ImageCompressionSkipReason): ImageCompressionItem => ({
+ entityType: target.entityType,
+ entityId: target.entityId,
+ title: target.title,
+ mime: target.mime,
+ originalSize,
+ newSize: originalSize,
+ compressed: false,
+ skipReason
+ });
+
+ // Protected content cannot even be read without a session, so it is the one skip decided
+ // without a size to report; every other one still reports what the image weighs.
+ if (target.skip === "protected") {
+ return skipped(0, "protected");
+ }
+
+ // One image failing is reported as that image's own skip and nothing more: the images after it
+ // in the same run are still worth compressing.
+ let content: Uint8Array | undefined;
+
+ try {
+ content = target.getContent();
+
+ if (target.skip) {
+ return skipped(content.byteLength, target.skip);
+ }
+
+ const outcome = await getImageProvider().compressImage(content, request);
+
+ if (!outcome.compressed) {
+ return skipped(content.byteLength, outcome.reason);
+ }
+
+ // The compression itself is asynchronous, so the write is a separate transaction of its
+ // own rather than one held open across it.
+ getSql().transactional(() => target.save(outcome.buffer, outcome.format.mime));
+
+ getLog().info(
+ `Compressed ${target.entityType} '${target.entityId}' from ${content.byteLength} to ${outcome.buffer.byteLength} bytes.`
+ );
+
+ return {
+ entityType: target.entityType,
+ entityId: target.entityId,
+ title: target.title,
+ mime: outcome.format.mime,
+ originalSize: content.byteLength,
+ newSize: outcome.buffer.byteLength,
+ compressed: true
+ };
+ } catch (e: unknown) {
+ logFailure(target, e);
+ return skipped(content?.byteLength ?? 0, "error");
+ }
+}
+
+function logFailure(target: CompressionTarget, e: unknown) {
+ const error = e as Error;
+
+ getLog().error(`Failed to compress ${target.entityType} '${target.entityId}': ${error?.stack ?? error}`);
+}
+
+function summarize(items: ImageCompressionItem[]): ImageCompressionResponse {
+ const originalSize = items.reduce((total, item) => total + item.originalSize, 0);
+ const newSize = items.reduce((total, item) => total + item.newSize, 0);
+
+ return {
+ items,
+ compressedCount: items.filter((item) => item.compressed).length,
+ skippedCount: items.filter((item) => !item.compressed).length,
+ originalSize,
+ newSize,
+ savedSize: originalSize - newSize
+ };
+}
+
+export default {
+ compressNoteImages,
+ compressAttachmentImage,
+ resolveCompressionRequest
+};
diff --git a/packages/trilium-core/src/services/image_provider.spec.ts b/packages/trilium-core/src/services/image_provider.spec.ts
index 6d57dec942..125c42aa1f 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 { ImageProvider, ProcessedImage } from "./image_provider.js";
+import type { ImageCompressionOutcome, ImageProvider, ProcessedImage } from "./image_provider.js";
describe("image provider (core)", () => {
// The core bootstrap installs a real image provider, so to exercise the
@@ -16,6 +16,10 @@ describe("image provider (core)", () => {
processImage: vi.fn(async (): Promise<ProcessedImage> => ({
buffer: new Uint8Array(),
format: { ext: "png", mime: "image/png" }
+ })),
+ compressImage: vi.fn(async (): Promise<ImageCompressionOutcome> => ({
+ compressed: false,
+ reason: "no-gain"
}))
};
mod.initImageProvider(fake);
diff --git a/packages/trilium-core/src/services/image_provider.ts b/packages/trilium-core/src/services/image_provider.ts
index 10649c7615..c886b304d0 100644
--- a/packages/trilium-core/src/services/image_provider.ts
+++ b/packages/trilium-core/src/services/image_provider.ts
@@ -4,6 +4,8 @@
* Standalone uses simple format detection without compression.
*/
+import type { ImageCompressionSkipReason } from "@triliumnext/commons";
+
export interface ImageFormat {
ext: string;
mime: string;
@@ -14,6 +16,23 @@ export interface ProcessedImage {
format: ImageFormat;
}
+/**
+ * A fully resolved {@link ImageCompressionOptions} — every fallback already applied, so a provider
+ * never has to reach for an option itself.
+ */
+export interface ImageCompressionRequest {
+ /** Longest edge in pixels; a larger image is scaled down to fit. */
+ maxWidthHeight: number;
+ /** JPEG quality, 10 to 100. */
+ quality: number;
+ /** Whether a lossless source (PNG) may be re-encoded as JPEG. */
+ convertLossless: boolean;
+}
+
+export type ImageCompressionOutcome =
+ | { compressed: true; buffer: Uint8Array; format: ImageFormat }
+ | { compressed: false; reason: ImageCompressionSkipReason };
+
export interface ImageProvider {
/**
* Detect image format from buffer.
@@ -28,6 +47,19 @@ export interface ImageProvider {
* @returns Processed image buffer and detected format
*/
processImage(buffer: Uint8Array, originalName: string, shrink: boolean): Promise<ProcessedImage>;
+
+ /**
+ * Recompress an image the user has explicitly asked to shrink, ignoring the `compressImages`
+ * option — that option governs automatic shrinking on import, and this is a deliberate act.
+ *
+ * Implementations decide nothing about *which* images to visit; they only answer for the one
+ * buffer handed to them, and say why when they leave it alone. The buffer is returned only when
+ * it genuinely came out smaller, so a caller can always replace the original with it.
+ *
+ * @param buffer - Raw image data
+ * @param request - Fully resolved compression parameters
+ */
+ compressImage(buffer: Uint8Array, request: ImageCompressionRequest): Promise<ImageCompressionOutcome>;
}
let imageProvider: ImageProvider | null = null;