Skip to content

Build your personal knowledge base with Trilium Notes

core/image compression: add image stats for notes

Adorian Doranb443cdd4a1b5
diff --git a/apps/server/src/services/image_inventory.spec.ts b/apps/server/src/services/image_inventory.spec.ts
new file mode 100644
index 0000000000..c54ee78739
--- /dev/null
+++ b/apps/server/src/services/image_inventory.spec.ts
@@ -0,0 +1,290 @@
+import type { ImageInventoryResponse } 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 inventory endpoint against real notes and attachments holding real image bytes, so
+ * what it reports is read off actual headers rather than anything the test arranged.
+ *
+ * The service itself is runtime-agnostic — it never decodes — but the fixtures are easiest to build
+ * with the image library, which is why the spec lives here.
+ */
+let api: CoreApiTester;
+
+/** 600x400, comfortably over the bounds these tests measure against. */
+let widePng: Uint8Array;
+let wideJpeg: Uint8Array;
+/** 100x80, comfortably under them. */
+let smallPng: Uint8Array;
+/** Not a format anything can compress. */
+const gif = Uint8Array.from(
+ Buffer.from("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7", "base64")
+);
+const svg = new TextEncoder().encode(`<svg xmlns="http://www.w3.org/2000/svg"><rect/></svg>`);
+
+beforeAll(async () => {
+ widePng = await paint(600, 400, "image/png");
+ wideJpeg = await paint(600, 400, "image/jpeg");
+ smallPng = await paint(100, 80, "image/png");
+}, 60000);
+
+async function paint(width: number, height: number, mime: "image/png" | "image/jpeg"): Promise<Uint8Array> {
+ const image = new Jimp({ width, height, color: 0x000000ff });
+ for (let x = 0; x < width; x++) {
+ for (let y = 0; y < height; y++) {
+ const r = Math.round(128 + 127 * Math.sin(x / 40));
+ const g = Math.round(128 + 127 * Math.sin(y / 30));
+ const b = Math.round(128 + 127 * Math.sin((x + y) / 50));
+ image.setPixelColor((((r << 24) | (g << 16) | (b << 8) | 0xff) >>> 0), x, y);
+ }
+ }
+
+ return new Uint8Array(await image.getBuffer(mime));
+}
+
+afterEach(() => {
+ cls.init(() => options.setOption("imageMaxWidthHeight", "2000"));
+});
+
+const inventoryOf = (noteId: string, query = "") =>
+ api.get<ImageInventoryResponse>(`/api/notes/${noteId}/image-inventory${query}`);
+
+describe("image inventory (GET /api/notes/:noteId/image-inventory)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ it("404s for a note that does not exist", async () => {
+ expect((await inventoryOf("missingNote123")).status).toBe(404);
+ });
+
+ it("reports nothing at all for a note holding no images", async () => {
+ const { noteId } = await createTextNote(api);
+
+ const res = await inventoryOf(noteId);
+
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({
+ total: { count: 0, size: 0 },
+ compressible: { count: 0, size: 0 },
+ oversized: { count: 0, size: 0 },
+ formats: [],
+ unreadable: 0
+ });
+ });
+
+ it("counts and weighs the images a note holds, format by format", async () => {
+ const { noteId } = await createTextNote(api);
+ await addAttachment(noteId, "a.png", widePng);
+ await addAttachment(noteId, "b.png", smallPng);
+ await addAttachment(noteId, "c.jpg", wideJpeg, "image/jpeg");
+ // Not an image at all: attachments of other roles are no part of the reading.
+ await addAttachment(noteId, "notes.txt", new Uint8Array([ 1, 2, 3 ]), "text/plain", "file");
+
+ const res = await inventoryOf(noteId);
+
+ expect(res.body.total.count).toBe(3);
+ expect(res.body.total.size).toBe(widePng.byteLength + smallPng.byteLength + wideJpeg.byteLength);
+ // Every one of them is a format a run could act on.
+ expect(res.body.compressible).toEqual(res.body.total);
+
+ expect(res.body.formats).toEqual([
+ { format: "png", count: 2, size: widePng.byteLength + smallPng.byteLength },
+ { format: "jpg", count: 1, size: wideJpeg.byteLength }
+ ]);
+ });
+
+ it("orders the formats by what they weigh, the reason for looking at all", async () => {
+ const { noteId } = await createTextNote(api);
+ await addAttachment(noteId, "small.png", smallPng);
+ await addAttachment(noteId, "big.jpg", wideJpeg, "image/jpeg");
+
+ const res = await inventoryOf(noteId);
+
+ expect(res.body.formats.map((entry) => entry.format)).toEqual([ "jpg", "png" ]);
+ });
+
+ it("counts a format nothing can compress, without calling it compressible", async () => {
+ const { noteId } = await createTextNote(api);
+ await addAttachment(noteId, "a.png", widePng);
+ await addAttachment(noteId, "b.gif", gif, "image/gif");
+ await addAttachment(noteId, "c.svg", svg, "image/svg+xml");
+
+ const res = await inventoryOf(noteId);
+
+ // All three are images the note holds; only one is an image a run could act on.
+ expect(res.body.total.count).toBe(3);
+ expect(res.body.compressible).toEqual({ count: 1, size: widePng.byteLength });
+ expect(res.body.formats.map((entry) => entry.format).sort()).toEqual([ "gif", "png", "svg" ]);
+ });
+
+ describe("what counts as oversized", () => {
+ it("measures the longest edge against the given bound", async () => {
+ const { noteId } = await createTextNote(api);
+ await addAttachment(noteId, "wide.png", widePng);
+ await addAttachment(noteId, "small.png", smallPng);
+
+ const res = await inventoryOf(noteId, "?maxWidthHeight=500");
+
+ expect(res.body.oversized).toEqual({ count: 1, size: widePng.byteLength });
+ expect(res.body.maxWidthHeight).toBe(500);
+ });
+
+ it("counts none once the bound is above them all", async () => {
+ const { noteId } = await createTextNote(api);
+ await addAttachment(noteId, "wide.png", widePng);
+
+ expect((await inventoryOf(noteId, "?maxWidthHeight=1000")).body.oversized.count).toBe(0);
+ });
+
+ it("falls back to the imageMaxWidthHeight option when no bound is given", async () => {
+ cls.init(() => options.setOption("imageMaxWidthHeight", "500"));
+ const { noteId } = await createTextNote(api);
+ await addAttachment(noteId, "wide.png", widePng);
+
+ const res = await inventoryOf(noteId);
+
+ expect(res.body.maxWidthHeight).toBe(500);
+ expect(res.body.oversized.count).toBe(1);
+ });
+
+ it("never counts an image no bound could reach", async () => {
+ const { noteId } = await createTextNote(api);
+ // A GIF is never resized, whatever its dimensions, so it is never oversized either.
+ await addAttachment(noteId, "a.gif", gif, "image/gif");
+
+ expect((await inventoryOf(noteId, "?maxWidthHeight=1")).body.oversized.count).toBe(0);
+ });
+ });
+
+ describe("how far the reading reaches", () => {
+ it("counts an image note's own image, not its attachments", async () => {
+ const noteId = await createImageNote(widePng);
+
+ const res = await inventoryOf(noteId);
+
+ expect(res.body.total).toEqual({ count: 1, size: widePng.byteLength });
+ });
+
+ it("stops at the note unless asked to descend", async () => {
+ const { noteId } = await createTextNote(api);
+ await addAttachment(noteId, "own.png", smallPng);
+ await createImageNote(widePng, noteId);
+
+ expect((await inventoryOf(noteId)).body.total.count).toBe(1);
+ });
+
+ it("takes in the child notes' own images too, once descending", async () => {
+ const { noteId } = await createTextNote(api);
+ await addAttachment(noteId, "own.png", smallPng);
+ await addAttachment(noteId, "own.jpg", wideJpeg, "image/jpeg");
+ const childId = await createImageNote(widePng, noteId);
+ await createImageNote(smallPng, childId);
+
+ const res = await inventoryOf(noteId, "?recursive=true");
+
+ // Two attachments here, plus the child image note and the grandchild.
+ expect(res.body.total.count).toBe(4);
+ expect(res.body.formats.find((entry) => entry.format === "jpg")).toEqual({
+ format: "jpg", count: 1, size: wideJpeg.byteLength
+ });
+ });
+
+ it("reads an image note as its own image alone, attachments hanging off it included", async () => {
+ const { noteId } = await createTextNote(api);
+ const childId = await createImageNote(widePng, noteId);
+ // An image note *is* its image; anything else attached to one is not a second picture
+ // of it. Pinned here because a run visits exactly the same set, and would skip this too.
+ await addAttachment(childId, "sidecar.jpg", wideJpeg, "image/jpeg");
+
+ const res = await inventoryOf(noteId, "?recursive=true");
+
+ expect(res.body.total).toEqual({ count: 1, size: widePng.byteLength });
+ });
+
+ it("counts a clone once, however often it is placed in the subtree", async () => {
+ const { noteId } = await createTextNote(api);
+ const childId = await createImageNote(widePng, noteId);
+ await api.put(`/api/notes/${childId}/clone-to-note/${noteId}`);
+
+ expect((await inventoryOf(noteId, "?recursive=true")).body.total.count).toBe(1);
+ });
+ });
+
+ it("counts the generated picture of a note, without offering it to be compressed", async () => {
+ const { noteId } = await createTextNote(api);
+ await addAttachment(noteId, "spreadsheet-export.png", widePng);
+ setNoteType(noteId, "spreadsheet");
+
+ const res = await inventoryOf(noteId);
+
+ // It is an image the note holds, so it is counted; a run would leave it alone, so it is not
+ // counted as something compressing could reach.
+ expect(res.body.total).toEqual({ count: 1, size: widePng.byteLength });
+ expect(res.body.compressible).toEqual({ count: 0, size: 0 });
+ });
+
+ it("says how many images it could not read rather than weighing them at nothing", async () => {
+ const noteId = await createImageNote(widePng);
+ cls.init(() => { becca.getNoteOrThrow(noteId).isProtected = true; });
+
+ const res = await inventoryOf(noteId);
+
+ expect(res.body.unreadable).toBe(1);
+ expect(res.body.total).toEqual({ count: 0, size: 0 });
+
+ cls.init(() => { becca.getNoteOrThrow(noteId).isProtected = false; });
+ });
+
+ it.each([
+ [ "a bound that is not a number", "?maxWidthHeight=lots" ],
+ [ "a fractional bound", "?maxWidthHeight=10.5" ],
+ [ "a bound of zero", "?maxWidthHeight=0" ],
+ [ "an empty bound", "?maxWidthHeight=" ],
+ [ "a recursive flag that is neither", "?recursive=perhaps" ]
+ ])("400s on %s rather than falling back to a default", async (_label, query) => {
+ const { noteId } = await createTextNote(api);
+
+ expect((await inventoryOf(noteId, query)).status).toBe(400);
+ });
+});
+
+/** 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,
+ mime = "image/png",
+ role = "image"
+): 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) {
+ cls.init(() => getSql().transactional(() => {
+ const note = becca.getNoteOrThrow(noteId);
+ note.type = type as never;
+ note.mime = "application/json";
+ note.save();
+ }));
+}
diff --git a/apps/server/src/services/image_provider.ts b/apps/server/src/services/image_provider.ts
index 2690074789..0a64763ae4 100644
--- a/apps/server/src/services/image_provider.ts
+++ b/apps/server/src/services/image_provider.ts
@@ -3,6 +3,7 @@
* Uses JIMP for image processing with full compression support.
*/
+import { IMAGE_COMPRESSIBLE_FORMATS } from "@triliumnext/commons";
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";
@@ -17,7 +18,7 @@ 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" ]);
+const COMPRESSIBLE_EXTENSIONS = new Set<string>(IMAGE_COMPRESSIBLE_FORMATS);
/**
* How large a palette the PNG quantizer may keep — deliberately the largest an indexed PNG can
diff --git a/apps/standalone/src/services/image_provider.ts b/apps/standalone/src/services/image_provider.ts
index 2fc3f1b5f8..dc13c6f1ec 100644
--- a/apps/standalone/src/services/image_provider.ts
+++ b/apps/standalone/src/services/image_provider.ts
@@ -5,78 +5,16 @@
*/
import type { ImageCompressionOutcome, ImageFormat, ImageProvider, ProcessedImage } from "@triliumnext/core";
+import { inspectImage, UNKNOWN_FORMAT } from "@triliumnext/core/src/services/image_inspect.js";
/**
- * Detect image type from buffer using magic bytes.
+ * Detect image type from buffer, delegating to the shared inspector so this runtime and the
+ * inventory recognise exactly the same formats by exactly the same bytes.
*/
function getImageTypeFromBuffer(buffer: Uint8Array): ImageFormat | null {
- if (buffer.length < 12) {
- return null;
- }
-
- // Check for SVG (text-based)
- if (isSvg(buffer)) {
- return { ext: "svg", mime: "image/svg+xml" };
- }
-
- // JPEG: FF D8 FF
- if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) {
- return { ext: "jpg", mime: "image/jpeg" };
- }
-
- // PNG: 89 50 4E 47 0D 0A 1A 0A
- if (
- buffer[0] === 0x89 &&
- buffer[1] === 0x50 &&
- buffer[2] === 0x4e &&
- buffer[3] === 0x47 &&
- buffer[4] === 0x0d &&
- buffer[5] === 0x0a &&
- buffer[6] === 0x1a &&
- buffer[7] === 0x0a
- ) {
- return { ext: "png", mime: "image/png" };
- }
-
- // GIF: "GIF"
- if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46) {
- return { ext: "gif", mime: "image/gif" };
- }
-
- // WebP: RIFF....WEBP
- if (
- buffer[0] === 0x52 &&
- buffer[1] === 0x49 &&
- buffer[2] === 0x46 &&
- buffer[3] === 0x46 &&
- buffer[8] === 0x57 &&
- buffer[9] === 0x45 &&
- buffer[10] === 0x42 &&
- buffer[11] === 0x50
- ) {
- return { ext: "webp", mime: "image/webp" };
- }
-
- // BMP: "BM"
- if (buffer[0] === 0x42 && buffer[1] === 0x4d) {
- return { ext: "bmp", mime: "image/bmp" };
- }
-
- return null;
-}
-
-/**
- * Check if buffer contains SVG content.
- */
-function isSvg(buffer: Uint8Array): boolean {
- const maxBytes = Math.min(buffer.length, 1000);
- let str = "";
- for (let i = 0; i < maxBytes; i++) {
- str += String.fromCharCode(buffer[i]);
- }
+ const { format, mime } = inspectImage(buffer);
- const trimmed = str.trim().toLowerCase();
- return trimmed.startsWith("<svg") || (trimmed.startsWith("<?xml") && trimmed.includes("<svg"));
+ return format === UNKNOWN_FORMAT ? null : { ext: format, mime };
}
export const standaloneImageProvider: ImageProvider = {
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.ts
index 6168063bb3..39404d8ab5 100644
--- a/packages/commons/src/lib/server_api.ts
+++ b/packages/commons/src/lib/server_api.ts
@@ -301,6 +301,49 @@ export const IMAGE_JPEG_HANDLINGS = [ "keep", "compress" ] as const;
export type ImageJpegHandling = (typeof IMAGE_JPEG_HANDLINGS)[number];
+/**
+ * The formats a compression run can act on at all. Named once and read by both the encoder that
+ * enforces it and the inventory that reports against it, so the two cannot come to disagree about
+ * which images are worth offering to compress.
+ */
+export const IMAGE_COMPRESSIBLE_FORMATS = [ "jpg", "png" ] as const;
+
+/** A count of images and what they weigh between them. */
+export interface ImageInventoryTally {
+ count: number;
+ /** Bytes, summed over the images counted. */
+ size: number;
+}
+
+export interface ImageInventoryFormat extends ImageInventoryTally {
+ /** Read from the content rather than the mime: "jpg", "png", "gif", "webp", "bmp", "svg". */
+ format: string;
+}
+
+/**
+ * What images a note holds, and what compressing them could reach.
+ *
+ * Measured over exactly the images a compression run with the same `recursive` setting would visit,
+ * so the two never describe different sets — see `getNoteImageInventory`.
+ */
+export interface ImageInventoryResponse {
+ /** Every image found, whatever its format. */
+ total: ImageInventoryTally;
+ /**
+ * Those a run could actually act on: a supported format, and not one of the generated pictures
+ * a canvas or spreadsheet note keeps, which are rebuilt on save and so left alone.
+ */
+ compressible: ImageInventoryTally;
+ /** Compressible images whose longest edge exceeds {@link maxWidthHeight}. */
+ oversized: ImageInventoryTally;
+ /** Every format found, heaviest first. */
+ formats: ImageInventoryFormat[];
+ /** What {@link oversized} was measured against. */
+ maxWidthHeight: number;
+ /** Images whose content could not be read — protected, with no session open. Counted nowhere else. */
+ unreadable: number;
+}
+
export interface ImageCompressionOptions {
/**
* Whether an image larger than {@link maxWidthHeight} is scaled down to fit. On its own this
diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.ts
index ac5cfdacc2..6d841c9ad5 100644
--- a/packages/trilium-core/src/index.ts
+++ b/packages/trilium-core/src/index.ts
@@ -109,6 +109,8 @@ export { getPlatform, type PlatformProvider } from "./services/platform";
export { InAppHelpProvider } from "./services/in_app_help";
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 { default as imageInventoryService, type ImageInventoryOptions } from "./services/image_inventory";
+export { inspectImage, type InspectedImage, UNKNOWN_FORMAT } from "./services/image_inspect";
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 40c531008f..5d56bec3c5 100644
--- a/packages/trilium-core/src/routes/api/image.ts
+++ b/packages/trilium-core/src/routes/api/image.ts
@@ -10,6 +10,7 @@ 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 imageInventoryService from "../../services/image_inventory.js";
import { sanitizeSvg, SVG_CONTENT_SECURITY_POLICY } from "../../services/utils/index.js";
import { unwrapStringOrBuffer } from "../../services/utils/binary.js";
@@ -141,6 +142,25 @@ function updateImage(req: FileRequest<{ noteId: string }>) {
return { uploaded: true };
}
+/**
+ * What images the note holds and how much of that compressing could reach — the reading the
+ * compression dialog opens on, so that it can say whether a run is worth making.
+ */
+function getImageInventory(req: Request<{ noteId: string }>) {
+ const { recursive, maxWidthHeight } = req.query;
+
+ if (recursive !== undefined && recursive !== "true" && recursive !== "false") {
+ return [ 400, "recursive must be 'true' or 'false'." ];
+ }
+
+ // `Number` of anything unparseable is NaN, which the service rejects along with every other
+ // value that is not a whole number of pixels — so a bad query fails rather than falling back.
+ return imageInventoryService.getNoteImageInventory(req.params.noteId, {
+ recursive: recursive === "true",
+ maxWidthHeight: maxWidthHeight === undefined ? undefined : Number(maxWidthHeight)
+ });
+}
+
function compressNoteImages(req: Request<{ noteId: string }>) {
return imageCompressionService.compressNoteImages(req.params.noteId, readCompressionOptions(req));
}
@@ -154,6 +174,7 @@ export default {
returnImageFromRevision,
returnAttachedImage,
updateImage,
+ getImageInventory,
compressNoteImages,
compressAttachmentImage
};
diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.ts
index 3de583cb98..604b41e4b6 100644
--- a/packages/trilium-core/src/routes/index.ts
+++ b/packages/trilium-core/src/routes/index.ts
@@ -131,6 +131,8 @@ 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);
+ // A reading rather than a run: headers only, so it is cheap enough to open a dialog with.
+ apiRoute(GET, "/api/notes/:noteId/image-inventory", imageRoute.getImageInventory);
// 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);
diff --git a/packages/trilium-core/src/services/image_compression.ts b/packages/trilium-core/src/services/image_compression.ts
index 5cc75cd789..eae54f0e7c 100644
--- a/packages/trilium-core/src/services/image_compression.ts
+++ b/packages/trilium-core/src/services/image_compression.ts
@@ -72,10 +72,6 @@ export async function compressAttachmentImage(attachmentId: string, options?: Im
export function resolveCompressionRequest(options: ImageCompressionOptions = {}): ImageCompressionRequest {
const { resize, maxWidthHeight, jpegHandling, pngHandling, quality, conversionQuality } = 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.`);
- }
-
requireQuality(quality, "quality");
requireQuality(conversionQuality, "conversionQuality");
requireBoolean(resize, "resize");
@@ -87,7 +83,7 @@ export function resolveCompressionRequest(options: ImageCompressionOptions = {})
// be compressed, and narrowing that down is what the fields are for. For a PNG that means
// being made smaller without ceasing to be one.
resize: resize ?? true,
- maxWidthHeight: maxWidthHeight ?? optionService.getOptionInt("imageMaxWidthHeight"),
+ maxWidthHeight: resolveMaxWidthHeight(maxWidthHeight),
jpegHandling: jpegHandling ?? "compress",
pngHandling: pngHandling ?? "optimize",
quality: quality ?? defaultQuality(),
@@ -95,6 +91,22 @@ export function resolveCompressionRequest(options: ImageCompressionOptions = {})
};
}
+/**
+ * The bound to measure images against, validated and filled in. Shared with the inventory, so what
+ * it reports as oversized is oversized by exactly the rule a run would apply.
+ */
+export function resolveMaxWidthHeight(maxWidthHeight: number | undefined): number {
+ if (maxWidthHeight === undefined) {
+ return optionService.getOptionInt("imageMaxWidthHeight");
+ }
+
+ if (!Number.isInteger(maxWidthHeight) || maxWidthHeight < MIN_MAX_WIDTH_HEIGHT) {
+ throw new ValidationError(`maxWidthHeight must be an integer of ${MIN_MAX_WIDTH_HEIGHT} or above.`);
+ }
+
+ return maxWidthHeight;
+}
+
function requireBoolean(value: unknown, name: string) {
if (value !== undefined && typeof value !== "boolean") {
throw new ValidationError(`${name} must be a boolean.`);
@@ -137,7 +149,7 @@ function defaultQuality(): number {
* (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 {
+export interface CompressionTarget {
entityType: "note" | "attachment";
entityId: string;
title: string;
@@ -156,7 +168,7 @@ interface CompressionTarget {
* `getSubtree` visits each note once however many placements it has, leaves the hidden subtree out
* and does not resolve search notes — the run follows the tree, not what a query happens to match.
*/
-function collectNoteTargets(note: BNote, recursive: boolean): CompressionTarget[] {
+export function collectNoteTargets(note: BNote, recursive: boolean): CompressionTarget[] {
if (!recursive) {
return ownTargetsOf(note);
}
diff --git a/packages/trilium-core/src/services/image_inspect.spec.ts b/packages/trilium-core/src/services/image_inspect.spec.ts
new file mode 100644
index 0000000000..9c1e5e0244
--- /dev/null
+++ b/packages/trilium-core/src/services/image_inspect.spec.ts
@@ -0,0 +1,127 @@
+import { describe, expect, it } from "vitest";
+
+import { inspectImage, UNKNOWN_FORMAT } from "./image_inspect.js";
+
+/**
+ * Hand-built headers rather than real images: the point of this module is that it reads the bytes
+ * and never decodes, so the bytes are what the tests should be made of. It also keeps the spec
+ * runnable on every runtime, having no image library behind it.
+ */
+
+/** A PNG signature followed by an IHDR chunk stating the given size. */
+function png(width: number, height: number): Uint8Array {
+ return Uint8Array.from([
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
+ 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
+ ...uint32(width), ...uint32(height),
+ 0x08, 0x06, 0x00, 0x00, 0x00
+ ]);
+}
+
+/**
+ * A JPEG made of the segments that matter: optionally something ahead of the frame header, then
+ * the frame header itself, which is where the size is stated.
+ */
+function jpeg(width: number, height: number, { marker = 0xc0, before = [] as number[] } = {}): Uint8Array {
+ return Uint8Array.from([
+ 0xff, 0xd8,
+ ...before,
+ 0xff, marker, 0x00, 0x11, 0x08,
+ (height >> 8) & 0xff, height & 0xff,
+ (width >> 8) & 0xff, width & 0xff,
+ 0x03, 0x01, 0x11, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01
+ ]);
+}
+
+/** An APP1 segment of `length` payload bytes, standing in for the EXIF a camera writes. */
+function app1(length: number): number[] {
+ return [ 0xff, 0xe1, ((length + 2) >> 8) & 0xff, (length + 2) & 0xff, ...new Array(length).fill(0) ];
+}
+
+function uint32(value: number): number[] {
+ return [ (value >>> 24) & 0xff, (value >>> 16) & 0xff, (value >>> 8) & 0xff, value & 0xff ];
+}
+
+function bytes(...values: number[]): Uint8Array {
+ // Padded past the length below which nothing is read at all.
+ return Uint8Array.from([ ...values, ...new Array(Math.max(0, 16 - values.length)).fill(0) ]);
+}
+
+const text = (value: string) => new TextEncoder().encode(value);
+
+describe("inspectImage", () => {
+ it("identifies the formats a note can hold, with their mime types", () => {
+ expect(inspectImage(png(1, 1))).toMatchObject({ format: "png", mime: "image/png" });
+ expect(inspectImage(jpeg(1, 1))).toMatchObject({ format: "jpg", mime: "image/jpeg" });
+ expect(inspectImage(bytes(0x47, 0x49, 0x46, 0x38, 0x39, 0x61))).toMatchObject({ format: "gif", mime: "image/gif" });
+ expect(inspectImage(bytes(0x42, 0x4d))).toMatchObject({ format: "bmp", mime: "image/bmp" });
+ expect(inspectImage(bytes(0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50)))
+ .toMatchObject({ format: "webp", mime: "image/webp" });
+ expect(inspectImage(text("<svg xmlns='http://www.w3.org/2000/svg'></svg>")))
+ .toMatchObject({ format: "svg", mime: "image/svg+xml" });
+ });
+
+ it("recognises an SVG behind an XML declaration", () => {
+ expect(inspectImage(text("<?xml version='1.0'?>\n<svg></svg>")).format).toBe("svg");
+ // A declaration introducing something else is not one.
+ expect(inspectImage(text("<?xml version='1.0'?><html></html>")).format).toBe(UNKNOWN_FORMAT);
+ });
+
+ it.each([
+ [ "an unrecognisable buffer", () => bytes(1, 2, 3, 4, 5, 6, 7, 8) ],
+ [ "a buffer too short to hold any header", () => Uint8Array.from([ 0x89, 0x50, 0x4e ]) ],
+ [ "an empty buffer", () => new Uint8Array() ]
+ ])("answers %s as unknown, with a fallback mime", (_label, build) => {
+ expect(inspectImage(build())).toMatchObject({
+ format: UNKNOWN_FORMAT,
+ mime: "application/octet-stream",
+ width: null,
+ height: null
+ });
+ });
+
+ describe("dimensions", () => {
+ it("reads a PNG from its IHDR chunk", () => {
+ expect(inspectImage(png(1920, 1080))).toMatchObject({ width: 1920, height: 1080 });
+ });
+
+ it("reads a JPEG from its frame header", () => {
+ expect(inspectImage(jpeg(800, 600))).toMatchObject({ width: 800, height: 600 });
+ });
+
+ it("walks past what a camera writes ahead of the frame header", () => {
+ // The reason the segments are walked rather than the marker searched for: EXIF and a
+ // thumbnail sit between the start of the file and the size it states.
+ expect(inspectImage(jpeg(800, 600, { before: app1(64) }))).toMatchObject({ width: 800, height: 600 });
+ });
+
+ it.each([
+ [ "baseline", 0xc0 ],
+ [ "progressive", 0xc2 ],
+ [ "arithmetic-coded", 0xc9 ]
+ ])("reads a %s frame header, every coding stating the same thing", (_label, marker) => {
+ expect(inspectImage(jpeg(320, 240, { marker }))).toMatchObject({ width: 320, height: 240 });
+ });
+
+ it("is not fooled by a table segment that is not a frame header at all", () => {
+ // 0xC4 is a Huffman table, which sits in the same marker range and states no size.
+ const withTable = jpeg(320, 240, { before: [ 0xff, 0xc4, 0x00, 0x06, 0, 0, 0, 0 ] });
+
+ expect(inspectImage(withTable)).toMatchObject({ width: 320, height: 240 });
+ });
+
+ it("measures nothing for formats no bound is ever applied to", () => {
+ // Identified but not measured: only the compressible formats are checked against a size.
+ expect(inspectImage(bytes(0x47, 0x49, 0x46, 0x38, 0x39, 0x61)))
+ .toMatchObject({ format: "gif", width: null, height: null });
+ });
+
+ it.each([
+ [ "a PNG cut off before its IHDR", () => Uint8Array.from([ ...png(10, 10) ].slice(0, 20)) ],
+ [ "a JPEG with no frame header", () => Uint8Array.from([ 0xff, 0xd8, ...app1(16) ]) ],
+ [ "a JPEG whose segments do not line up", () => Uint8Array.from([ 0xff, 0xd8, 0x12, 0x34, 0x56, 0x78, 0, 0, 0, 0, 0, 0 ]) ]
+ ])("answers no size for %s rather than guessing one", (_label, build) => {
+ expect(inspectImage(build())).toMatchObject({ width: null, height: null });
+ });
+ });
+});
diff --git a/packages/trilium-core/src/services/image_inspect.ts b/packages/trilium-core/src/services/image_inspect.ts
new file mode 100644
index 0000000000..3bdda73226
--- /dev/null
+++ b/packages/trilium-core/src/services/image_inspect.ts
@@ -0,0 +1,168 @@
+/**
+ * Reads what an image is and how large it is, from its header alone.
+ *
+ * Deliberately never decodes: an inventory has to walk every image a note holds, and decoding them
+ * to count them would cost more than compressing them. Pure byte inspection also means this works
+ * on every runtime, including the one with no image library at all.
+ */
+
+export interface InspectedImage {
+ /** "jpg", "png", "gif", "webp", "bmp", "svg", or {@link UNKNOWN_FORMAT}. */
+ format: string;
+ mime: string;
+ /**
+ * Pixel dimensions, or `null` where they were not read.
+ *
+ * Only read for the formats a compression run can act on, those being the only ones a size
+ * bound is ever measured against. Everything else is identified but not measured.
+ */
+ width: number | null;
+ height: number | null;
+}
+
+export const UNKNOWN_FORMAT = "unknown";
+
+/** Identifies `buffer`, and measures it where that is worth doing. */
+export function inspectImage(buffer: Uint8Array): InspectedImage {
+ const format = detectFormat(buffer);
+ const dimensions = format === "png" ? readPngDimensions(buffer)
+ : format === "jpg" ? readJpegDimensions(buffer)
+ : null;
+
+ return {
+ format,
+ mime: FORMAT_MIMES[format] ?? FORMAT_MIMES[UNKNOWN_FORMAT],
+ width: dimensions?.width ?? null,
+ height: dimensions?.height ?? null
+ };
+}
+
+/** The magic bytes each format opens with; SVG being text, it is recognised by its markup instead. */
+function detectFormat(buffer: Uint8Array): string {
+ // Shorter than any header worth reading, so nothing can be told from it.
+ if (buffer.length < 12) {
+ return UNKNOWN_FORMAT;
+ }
+
+ if (isSvg(buffer)) {
+ return "svg";
+ }
+
+ if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) {
+ return "jpg";
+ }
+
+ if (startsWith(buffer, [ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a ])) {
+ return "png";
+ }
+
+ if (startsWith(buffer, [ 0x47, 0x49, 0x46 ])) {
+ return "gif";
+ }
+
+ // RIFF....WEBP: the four-byte tag sits past the chunk size.
+ if (startsWith(buffer, [ 0x52, 0x49, 0x46, 0x46 ])
+ && buffer[8] === 0x57 && buffer[9] === 0x45 && buffer[10] === 0x42 && buffer[11] === 0x50) {
+ return "webp";
+ }
+
+ return startsWith(buffer, [ 0x42, 0x4d ]) ? "bmp" : UNKNOWN_FORMAT;
+}
+
+/** The IHDR chunk is required to come first, so both figures sit at a fixed offset. */
+function readPngDimensions(buffer: Uint8Array): { width: number; height: number } | null {
+ if (buffer.length < 24) {
+ return null;
+ }
+
+ return { width: readUint32(buffer, 16), height: readUint32(buffer, 20) };
+}
+
+/**
+ * Walks the segment structure to the frame header, which is where a JPEG states its size — and
+ * which sits after any EXIF or thumbnail the file happens to carry, so it has to be walked to
+ * rather than searched for.
+ */
+function readJpegDimensions(buffer: Uint8Array): { width: number; height: number } | null {
+ let offset = 2;
+
+ while (offset + 3 < buffer.length) {
+ if (buffer[offset] !== 0xff) {
+ // Out of step with the segments; nothing further can be read with any confidence.
+ return null;
+ }
+
+ const marker = buffer[offset + 1];
+
+ if (marker === 0xff) {
+ // Fill bytes are allowed to pad ahead of a marker.
+ offset++;
+ continue;
+ }
+
+ if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {
+ // Standalone markers carry no length to skip by.
+ offset += 2;
+ continue;
+ }
+
+ const length = (buffer[offset + 2] << 8) | buffer[offset + 3];
+
+ if (length < 2 || offset + 2 + length > buffer.length) {
+ return null;
+ }
+
+ if (isFrameHeader(marker)) {
+ // Precision, then height, then width.
+ return offset + 9 <= buffer.length
+ ? { width: (buffer[offset + 7] << 8) | buffer[offset + 8], height: (buffer[offset + 5] << 8) | buffer[offset + 6] }
+ : null;
+ }
+
+ offset += 2 + length;
+ }
+
+ return null;
+}
+
+/**
+ * Every SOFn marker states the frame's size, whichever coding it introduces — so all of C0..CF
+ * count except the three that are not frame headers at all: DHT, JPG and DAC.
+ */
+function isFrameHeader(marker: number): boolean {
+ return marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc;
+}
+
+/** Recognises SVG by its opening markup, allowing for an XML declaration ahead of it. */
+function isSvg(buffer: Uint8Array): boolean {
+ let text = "";
+
+ for (let index = 0; index < Math.min(buffer.length, SVG_SNIFF_BYTES); index++) {
+ text += String.fromCharCode(buffer[index]);
+ }
+
+ const trimmed = text.trim().toLowerCase();
+
+ return trimmed.startsWith("<svg") || (trimmed.startsWith("<?xml") && trimmed.includes("<svg"));
+}
+
+function startsWith(buffer: Uint8Array, signature: number[]): boolean {
+ return signature.every((byte, index) => buffer[index] === byte);
+}
+
+function readUint32(buffer: Uint8Array, offset: number): number {
+ return ((buffer[offset] << 24) | (buffer[offset + 1] << 16) | (buffer[offset + 2] << 8) | buffer[offset + 3]) >>> 0;
+}
+
+/** Far enough into the file to clear an XML declaration and any comments before the root element. */
+const SVG_SNIFF_BYTES = 1000;
+
+const FORMAT_MIMES: Record<string, string> = {
+ jpg: "image/jpeg",
+ png: "image/png",
+ gif: "image/gif",
+ webp: "image/webp",
+ bmp: "image/bmp",
+ svg: "image/svg+xml",
+ [UNKNOWN_FORMAT]: "application/octet-stream"
+};
diff --git a/packages/trilium-core/src/services/image_inventory.ts b/packages/trilium-core/src/services/image_inventory.ts
new file mode 100644
index 0000000000..186e8429ad
--- /dev/null
+++ b/packages/trilium-core/src/services/image_inventory.ts
@@ -0,0 +1,130 @@
+/**
+ * What images a note holds, and how much of that compressing could reach.
+ *
+ * Answers the question the compression dialog cannot answer for itself — is this worth running, and
+ * on how much — without running anything. The images counted are exactly those a run with the same
+ * `recursive` setting would visit, because both come from the same {@link collectNoteTargets}: an
+ * inventory that described a different set from the operation it precedes would be worse than none.
+ *
+ * Headers only, never a decode. Walking a subtree to identify and measure every image has to stay
+ * far cheaper than compressing them, or nothing would open the dialog with it.
+ */
+
+import {
+ IMAGE_COMPRESSIBLE_FORMATS,
+ type ImageInventoryFormat,
+ type ImageInventoryResponse,
+ type ImageInventoryTally
+} from "@triliumnext/commons";
+
+import becca from "../becca/becca.js";
+import { NotFoundError } from "../errors.js";
+import {
+ collectNoteTargets,
+ type CompressionTarget,
+ resolveMaxWidthHeight,
+ resolveRecursive
+} from "./image_compression.js";
+import { inspectImage } from "./image_inspect.js";
+
+export interface ImageInventoryOptions {
+ /** Whether the note's whole subtree is counted, rather than the note on its own. */
+ recursive?: boolean;
+ /** The longest edge to measure against. Omitted, it falls back to the `imageMaxWidthHeight` option. */
+ maxWidthHeight?: number;
+}
+
+export function getNoteImageInventory(noteId: string, options: ImageInventoryOptions = {}): ImageInventoryResponse {
+ const note = becca.getNote(noteId);
+
+ if (!note) {
+ throw new NotFoundError(`Note '${noteId}' was not found.`);
+ }
+
+ const maxWidthHeight = resolveMaxWidthHeight(options.maxWidthHeight);
+ const targets = collectNoteTargets(note, resolveRecursive(options));
+
+ const total = emptyTally();
+ const compressible = emptyTally();
+ const oversized = emptyTally();
+ const formats = new Map<string, ImageInventoryFormat>();
+ let unreadable = 0;
+
+ for (const target of targets) {
+ const content = readContent(target);
+
+ if (!content) {
+ unreadable++;
+ continue;
+ }
+
+ const { format, width, height } = inspectImage(content);
+ const size = content.byteLength;
+
+ add(total, size);
+ add(tallyFor(formats, format), size);
+
+ // Everything above counts what is *there*; from here down, only what a run would act on —
+ // so a format nothing can compress, and a picture a note regenerates on save, are both out.
+ if (target.skip || !(IMAGE_COMPRESSIBLE_FORMATS as readonly string[]).includes(format)) {
+ continue;
+ }
+
+ add(compressible, size);
+
+ if (width !== null && height !== null && Math.max(width, height) > maxWidthHeight) {
+ add(oversized, size);
+ }
+ }
+
+ return {
+ total,
+ compressible,
+ oversized,
+ // Heaviest first: what a note's images weigh is the reason to be looking at all.
+ formats: [ ...formats.values() ].sort((a, b) => b.size - a.size),
+ maxWidthHeight,
+ unreadable
+ };
+}
+
+/**
+ * The image's bytes, or `null` where they cannot be had — protected content with no session open,
+ * and any read that fails for a reason this has no use for. Counting an image it could not measure
+ * would put a size of zero into the totals, which is worse than saying it went unread.
+ */
+function readContent(target: CompressionTarget): Uint8Array | null {
+ if (target.skip === "protected") {
+ return null;
+ }
+
+ try {
+ return target.getContent();
+ } catch {
+ return null;
+ }
+}
+
+function tallyFor(formats: Map<string, ImageInventoryFormat>, format: string): ImageInventoryFormat {
+ const existing = formats.get(format);
+
+ if (existing) {
+ return existing;
+ }
+
+ const created = { format, count: 0, size: 0 };
+ formats.set(format, created);
+
+ return created;
+}
+
+function add(tally: ImageInventoryTally, size: number) {
+ tally.count++;
+ tally.size += size;
+}
+
+function emptyTally(): ImageInventoryTally {
+ return { count: 0, size: 0 };
+}
+
+export default { getNoteImageInventory };