Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
core/image compression: add image stats for a given image
Adorian Doran938c4cf553c4
diff --git a/apps/server/src/services/image_info.spec.ts b/apps/server/src/services/image_info.spec.tsnew file mode 100644index 0000000000..270df62362--- /dev/null+++ b/apps/server/src/services/image_info.spec.ts@@ -0,0 +1,216 @@+import type { ImageInfoResponse } from "@triliumnext/commons";+import { becca, cls, getSql } 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 { beforeAll, describe, expect, it } from "vitest";++/**+ * Drives the single-image info endpoints against real notes and attachments holding real bytes, so+ * every figure is read off an actual header rather than one the test arranged.+ */+let api: CoreApiTester;++let png: Uint8Array;+let jpeg: Uint8Array;+let transparentPng: Uint8Array;+const gif = Uint8Array.from(+ Buffer.from("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7", "base64")+);++beforeAll(async () => {+ api = CoreApiTester.build();+ png = await paint(320, 240, "image/png", 0xff);+ jpeg = await paint(320, 240, "image/jpeg", 0xff);+ transparentPng = await paint(64, 48, "image/png", 0x80);+}, 60000);++async function paint(width: number, height: number, mime: "image/png" | "image/jpeg", alpha: number): Promise<Uint8Array> {+ const image = new Jimp({ width, height, color: (0x3366cc00 | alpha) >>> 0 });+ for (let x = 0; x < width; x++) {+ for (let y = 0; y < height; y++) {+ const r = Math.round(128 + 127 * Math.sin(x / 20));+ const g = Math.round(128 + 127 * Math.sin(y / 15));+ image.setPixelColor((((r << 24) | (g << 16) | (0x80 << 8) | alpha) >>> 0), x, y);+ }+ }++ return new Uint8Array(await image.getBuffer(mime, { quality: 60 }));+}++const noteInfo = (noteId: string) => api.get<ImageInfoResponse>(`/api/notes/${noteId}/image-info`);+const attachmentInfo = (attachmentId: string) =>+ api.get<ImageInfoResponse>(`/api/attachments/${attachmentId}/image-info`);++describe("image info (GET /api/notes/:noteId/image-info)", () => {+ it("404s for a note that does not exist", async () => {+ expect((await noteInfo("missingNote123")).status).toBe(404);+ });++ it("400s for a note that is not an image", async () => {+ const { noteId } = await createTextNote(api);++ expect((await noteInfo(noteId)).status).toBe(400);+ });++ it("describes a PNG down to how its pixels are stored", async () => {+ const noteId = await createImageNote(png, "image/png");++ const res = await noteInfo(noteId);++ expect(res.status).toBe(200);+ expect(res.body).toMatchObject({+ entityType: "note",+ entityId: noteId,+ mime: "image/png",+ format: "png",+ detectedMime: "image/png",+ size: png.byteLength,+ width: 320,+ height: 240,+ bitDepth: 8,+ channels: 4,+ hasAlpha: true,+ indexed: false,+ // Nothing but a JPEG carries the tables a quality is read from.+ quality: null,+ compressible: true+ });+ });++ it("describes a JPEG, quality included", async () => {+ const noteId = await createImageNote(jpeg, "image/jpeg");++ const res = await noteInfo(noteId);++ expect(res.body).toMatchObject({+ format: "jpg",+ detectedMime: "image/jpeg",+ width: 320,+ height: 240,+ bitDepth: 8,+ // Three components, and never an alpha channel whatever the source had.+ channels: 3,+ hasAlpha: false,+ indexed: false,+ compressible: true+ });+ // Read back off its own quantization tables, so it lands on what it was written at.+ expect(Math.abs((res.body.quality ?? 0) - 60)).toBeLessThanOrEqual(5);+ });++ it("reads the bytes rather than trusting the mime it is filed under", async () => {+ // A PNG stored under the wrong mime: both are reported, so the disagreement is visible.+ const noteId = await createImageNote(png, "image/jpeg");++ const res = await noteInfo(noteId);++ expect(res.body.mime).toBe("image/jpeg");+ expect(res.body.format).toBe("png");+ expect(res.body.detectedMime).toBe("image/png");+ });++ it("403s when the content is protected and no session is open", async () => {+ const noteId = await createImageNote(png, "image/png");+ cls.init(() => { becca.getNoteOrThrow(noteId).isProtected = true; });++ // A row of nulls would pass for an image that simply says nothing about itself.+ expect((await noteInfo(noteId)).status).toBe(403);++ cls.init(() => { becca.getNoteOrThrow(noteId).isProtected = false; });+ });+});++describe("image info (GET /api/attachments/:attachmentId/image-info)", () => {+ it("404s for an attachment that does not exist", async () => {+ expect((await attachmentInfo("missingAtt123")).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 ]), "text/plain", "file");++ expect((await attachmentInfo(attachmentId)).status).toBe(400);+ });++ it("describes an attachment exactly as it describes a note's own image", async () => {+ const { noteId } = await createTextNote(api);+ const attachmentId = await addAttachment(noteId, "shot.png", transparentPng);++ const res = await attachmentInfo(attachmentId);++ expect(res.body).toMatchObject({+ entityType: "attachment",+ entityId: attachmentId,+ title: "shot.png",+ format: "png",+ width: 64,+ height: 48,+ hasAlpha: true,+ compressible: true+ });+ });++ it("says what it can about a format nothing can compress, and no more", async () => {+ const { noteId } = await createTextNote(api);+ const attachmentId = await addAttachment(noteId, "a.gif", gif, "image/gif");++ const res = await attachmentInfo(attachmentId);++ expect(res.body).toMatchObject({+ format: "gif",+ size: gif.byteLength,+ width: 1,+ height: 1,+ // The header states a size and nothing else this has a use for.+ bitDepth: null,+ channels: null,+ quality: null,+ compressible: false+ });+ });++ it("reports an unreadable file as unknown rather than refusing to answer", async () => {+ const { noteId } = await createTextNote(api);+ const attachmentId = await addAttachment(noteId, "broken.png", new Uint8Array([ 1, 2, 3, 4 ]), "image/png");++ const res = await attachmentInfo(attachmentId);++ expect(res.status).toBe(200);+ expect(res.body).toMatchObject({+ format: "unknown",+ detectedMime: "application/octet-stream",+ size: 4,+ width: null,+ height: null,+ compressible: false+ });+ });+});++async function createImageNote(content: Uint8Array, mime: string): Promise<string> {+ const { noteId } = await createTextNote(api);++ cls.init(() => getSql().transactional(() => {+ const note = becca.getNoteOrThrow(noteId);+ note.type = "image";+ note.mime = mime;+ 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 ?? "";+ }));+}diff --git a/apps/server/src/services/image_provider.spec.ts b/apps/server/src/services/image_provider.spec.tsindex fe459ffef2..63f6eb9944 100644--- a/apps/server/src/services/image_provider.spec.ts+++ b/apps/server/src/services/image_provider.spec.ts@@ -1,9 +1,8 @@-import { cls, type ImageCompressionRequest, options } from '@triliumnext/core';+import { cls, estimateJpegQuality, type ImageCompressionRequest, options } from '@triliumnext/core';import { Jimp } from 'jimp';import { afterEach, beforeAll, describe, expect, it } from 'vitest';import { serverImageProvider } from './image_provider.js';-import { estimateJpegQuality } from './jpeg_quality.js';// is-svg / image-type / is-animated / jimp are all loaded by spec/setup.ts (which// imports serverImageProvider to initialise core), so they cannot be re-mockeddiff --git a/apps/server/src/services/image_provider.ts b/apps/server/src/services/image_provider.tsindex 0a64763ae4..0b9ada90b3 100644--- a/apps/server/src/services/image_provider.ts+++ b/apps/server/src/services/image_provider.ts@@ -4,7 +4,7 @@*/import { IMAGE_COMPRESSIBLE_FORMATS } from "@triliumnext/commons";-import { getLog, options as optionService } from "@triliumnext/core";+import { estimateJpegQuality, 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";@@ -12,8 +12,6 @@ import isSvg from "is-svg";import { Jimp } from "jimp";import * as UPNG from "upng-js";-import { estimateJpegQuality } from "./jpeg_quality.js";-const JPEG_FORMAT: ImageFormat = { ext: "jpg", mime: "image/jpeg" };const PNG_FORMAT: ImageFormat = { ext: "png", mime: "image/png" };diff --git a/apps/server/src/services/jpeg_quality.spec.ts b/apps/server/src/services/jpeg_quality.spec.tsindex bcd7e9c44c..b67d434b20 100644--- a/apps/server/src/services/jpeg_quality.spec.ts+++ b/apps/server/src/services/jpeg_quality.spec.ts@@ -1,8 +1,7 @@+import { estimateJpegQuality } from "@triliumnext/core";import { Jimp } from "jimp";import { beforeAll, describe, expect, it } from "vitest";-import { estimateJpegQuality } from "./jpeg_quality.js";-/*** Round-trips real JPEGs through the estimator: encode at a known quality, read it back off the* quantization table. Jimp's encoder scales the standard table the way libjpeg does, which is thediff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex 39404d8ab5..5483fd110a 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -308,6 +308,40 @@ export type ImageJpegHandling = (typeof IMAGE_JPEG_HANDLINGS)[number];*/export const IMAGE_COMPRESSIBLE_FORMATS = [ "jpg", "png" ] as const;+/**+ * What one image is, read from its own bytes.+ *+ * Every measurement is nullable and null means one thing throughout: the format does not state it,+ * or the file is too damaged to. Nothing here is a default standing in for something unread.+ */+export interface ImageInfoResponse {+ entityType: "note" | "attachment";+ entityId: string;+ title: string;+ /** The mime it is stored under, which is not always what the bytes turn out to say. */+ mime: string;+ /** What the bytes say it is: "jpg", "png", "gif", "webp", "bmp", "svg", "unknown". */+ format: string;+ /** The mime that format implies, for comparing against {@link mime}. */+ detectedMime: string;+ /** Bytes on disk. */+ size: number;+ width: number | null;+ height: number | null;+ /** Bits per channel — 8 for almost everything, 16 for a deep PNG. */+ bitDepth: number | null;+ /** Channels per pixel: 1 greyscale or indexed, 3 colour, 4 colour with alpha or CMYK. */+ channels: number | null;+ /** Whether the format stores an alpha channel; not whether any pixel actually uses it. */+ hasAlpha: boolean | null;+ /** Stored as a palette rather than colour per pixel — already quantized, in other words. */+ indexed: boolean | null;+ /** For a JPEG, the quality it appears to have been written at; null for anything else. */+ quality: number | null;+ /** Whether a compression run could act on it at all. */+ compressible: boolean;+}+/** A count of images and what they weigh between them. */export interface ImageInventoryTally {count: number;diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.tsindex 6d841c9ad5..fab709fea1 100644--- a/packages/trilium-core/src/index.ts+++ b/packages/trilium-core/src/index.ts@@ -110,6 +110,8 @@ 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 { default as imageInfoService } from "./services/image_info";+export { estimateJpegQuality } from "./services/jpeg_quality";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";diff --git a/packages/trilium-core/src/routes/api/image.ts b/packages/trilium-core/src/routes/api/image.tsindex 5d56bec3c5..63341a8a7d 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 imageInfoService from "../../services/image_info.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";@@ -142,6 +143,16 @@ function updateImage(req: FileRequest<{ noteId: string }>) {return { uploaded: true };}+/** What one image note's own image is: format, size, and how it is stored. */+function getNoteImageInfo(req: Request<{ noteId: string }>) {+ return imageInfoService.getNoteImageInfo(req.params.noteId);+}++/** The same for one image attachment. */+function getAttachmentImageInfo(req: Request<{ attachmentId: string }>) {+ return imageInfoService.getAttachmentImageInfo(req.params.attachmentId);+}+/*** 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.@@ -174,6 +185,8 @@ export default {returnImageFromRevision,returnAttachedImage,updateImage,+ getNoteImageInfo,+ getAttachmentImageInfo,getImageInventory,compressNoteImages,compressAttachmentImagediff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.tsindex 604b41e4b6..c2baa7d1ba 100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@ -131,7 +131,9 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRoutroute(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.+ // Readings rather than runs: headers only, so they are cheap enough to open a dialog with.+ apiRoute(GET, "/api/notes/:noteId/image-info", imageRoute.getNoteImageInfo);+ apiRoute(GET, "/api/attachments/:attachmentId/image-info", imageRoute.getAttachmentImageInfo);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.diff --git a/packages/trilium-core/src/services/image_info.ts b/packages/trilium-core/src/services/image_info.tsnew file mode 100644index 0000000000..3eeb0697ed--- /dev/null+++ b/packages/trilium-core/src/services/image_info.ts@@ -0,0 +1,85 @@+/**+ * What one named image is: its format, its dimensions, what it weighs, and how it is stored.+ *+ * The counterpart to the inventory, which answers the same question over a whole note. Both read+ * headers only and neither decodes, so opening either costs a blob read and nothing else.+ */++import { IMAGE_COMPRESSIBLE_FORMATS, type ImageInfoResponse } 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 { ForbiddenError, NotFoundError, ValidationError } from "../errors.js";+import { inspectImage } from "./image_inspect.js";+import { estimateJpegQuality } from "./jpeg_quality.js";+import { wrapStringOrBuffer } from "./utils/binary.js";++/** Describes an image note's own image. */+export function getNoteImageInfo(noteId: string): ImageInfoResponse {+ const note = becca.getNote(noteId);++ if (!note) {+ throw new NotFoundError(`Note '${noteId}' was not found.`);+ }++ if (note.type !== "image") {+ throw new ValidationError(`Note '${noteId}' is of type '${note.type}', but 'image' was expected.`);+ }++ return describe("note", noteId, note.title, note.mime, note);+}++/** Describes one image attachment. */+export function getAttachmentImageInfo(attachmentId: string): ImageInfoResponse {+ 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 describe("attachment", attachmentId, attachment.title, attachment.mime, attachment);+}++function describe(+ entityType: "note" | "attachment",+ entityId: string,+ title: string,+ mime: string,+ entity: BNote | BAttachment+): ImageInfoResponse {+ if (!entity.isContentAvailable()) {+ // Nothing here can be read without the content, and answering with a row of nulls would+ // pass for an image that simply says nothing about itself.+ throw new ForbiddenError(`Content of '${entityId}' is protected and no protected session is open.`);+ }++ const content = wrapStringOrBuffer(entity.getContent());+ const inspected = inspectImage(content);++ return {+ entityType,+ entityId,+ title,+ mime,+ format: inspected.format,+ detectedMime: inspected.mime,+ size: content.byteLength,+ width: inspected.width,+ height: inspected.height,+ bitDepth: inspected.bitDepth,+ channels: inspected.channels,+ hasAlpha: inspected.hasAlpha,+ indexed: inspected.indexed,+ // Only a JPEG carries the quantization tables this is read from; for everything else the+ // question does not arise, which is a different thing from an unreadable answer.+ quality: inspected.format === "jpg" ? estimateJpegQuality(content) : null,+ compressible: (IMAGE_COMPRESSIBLE_FORMATS as readonly string[]).includes(inspected.format)+ };+}++export default { getNoteImageInfo, getAttachmentImageInfo };diff --git a/packages/trilium-core/src/services/image_inspect.spec.ts b/packages/trilium-core/src/services/image_inspect.spec.tsindex 9c1e5e0244..73f8a6e832 100644--- a/packages/trilium-core/src/services/image_inspect.spec.ts+++ b/packages/trilium-core/src/services/image_inspect.spec.ts@@ -8,13 +8,13 @@ import { inspectImage, UNKNOWN_FORMAT } from "./image_inspect.js";* 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 {+/** A PNG signature followed by an IHDR chunk stating the given size, depth and colour type. */+function png(width: number, height: number, { depth = 8, colorType = 6 } = {}): 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+ depth, colorType, 0x00, 0x00, 0x00]);}@@ -110,10 +110,48 @@ describe("inspectImage", () => {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("reads a GIF from its screen descriptor, little-endian", () => {+ const gif = bytes(0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x20, 0x03, 0xc0, 0x02);++ expect(inspectImage(gif)).toMatchObject({ format: "gif", width: 800, height: 704 });+ });++ it("reads a BMP from its DIB header, an upside-down one included", () => {+ const bmp = new Uint8Array(30);+ bmp.set([ 0x42, 0x4d ]);+ // Width 640, then a negative height, which is how a top-down bitmap states 480.+ bmp.set([ 0x80, 0x02, 0x00, 0x00 ], 18);+ bmp.set([ 0x20, 0xfe, 0xff, 0xff ], 22);++ expect(inspectImage(bmp)).toMatchObject({ format: "bmp", width: 640, height: 480 });+ });++ it("measures nothing for a format whose header it does not read", () => {+ const webp = bytes(0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50);++ expect(inspectImage(webp)).toMatchObject({ format: "webp", width: null, height: null });+ });++ it.each([+ [ "greyscale", 0, { channels: 1, hasAlpha: false, indexed: false } ],+ [ "colour", 2, { channels: 3, hasAlpha: false, indexed: false } ],+ // Already quantized, which is the thing worth knowing before offering to quantize it.+ [ "a palette", 3, { channels: 1, hasAlpha: false, indexed: true } ],+ [ "greyscale with alpha", 4, { channels: 2, hasAlpha: true, indexed: false } ],+ [ "colour with alpha", 6, { channels: 4, hasAlpha: true, indexed: false } ]+ ])("reads a PNG storing %s", (_label, colorType, expected) => {+ expect(inspectImage(png(8, 8, { colorType }))).toMatchObject(expected);+ });++ it("reads how many bits a channel is given, a deep PNG included", () => {+ expect(inspectImage(png(8, 8, { depth: 8 })).bitDepth).toBe(8);+ expect(inspectImage(png(8, 8, { depth: 16 })).bitDepth).toBe(16);+ });++ it("reads a JPEG's precision and components, which never carry an alpha channel", () => {+ expect(inspectImage(jpeg(8, 8))).toMatchObject({+ bitDepth: 8, channels: 3, hasAlpha: false, indexed: false+ });});it.each([diff --git a/packages/trilium-core/src/services/image_inspect.ts b/packages/trilium-core/src/services/image_inspect.tsindex 3bdda73226..98e848c2c2 100644--- a/packages/trilium-core/src/services/image_inspect.ts+++ b/packages/trilium-core/src/services/image_inspect.ts@@ -6,37 +6,60 @@* on every runtime, including the one with no image library at all.*/+/**+ * Everything a header states. Every field past the format is nullable, and null means the same+ * thing throughout: this format does not say, or this file is too damaged to say — never a default+ * standing in for a measurement that was not taken.+ */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;+ /** Bits per channel, as the format stores them — 8 for almost everything, 16 for a deep PNG. */+ bitDepth: number | null;+ /** Channels per pixel: 1 greyscale or indexed, 3 colour, 4 colour with alpha or CMYK. */+ channels: number | null;+ /** Whether the format is storing an alpha channel; not whether any pixel actually uses it. */+ hasAlpha: boolean | null;+ /** Stored as a palette rather than as colour per pixel — already quantized, in other words. */+ indexed: boolean | null;}export const UNKNOWN_FORMAT = "unknown";-/** Identifies `buffer`, and measures it where that is worth doing. */+/** Identifies `buffer` and reads back whatever its header states about it. */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+ ...UNMEASURED,+ ...readHeader(format, buffer)};}+type ImageMeasurements = Omit<InspectedImage, "format" | "mime">;++/** What every field says before anything has been read: nothing measured, nothing assumed. */+const UNMEASURED: ImageMeasurements = {+ width: null, height: null, bitDepth: null, channels: null, hasAlpha: null, indexed: null+};++function readHeader(format: string, buffer: Uint8Array): Partial<ImageMeasurements> {+ switch (format) {+ case "png": return readPngHeader(buffer);+ case "jpg": return readJpegHeader(buffer);+ // Their dimensions sit at a fixed offset and are worth having; what they say about depth+ // needs a walk through palette and header variants that nothing here has a use for.+ case "gif": return readUint16LePair(buffer, 6, 8);+ case "bmp": return buffer.length >= 26 ? readUint32LePair(buffer, 18, 22) : {};+ default: return {};+ }+}+/** 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.@@ -69,13 +92,28 @@ function detectFormat(buffer: Uint8Array): string {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;+/**+ * The IHDR chunk is required to come first, so everything a PNG states about itself sits at a fixed+ * offset: size, then bits per channel, then the colour type the channels follow from.+ */+function readPngHeader(buffer: Uint8Array): Partial<ImageMeasurements> {+ if (buffer.length < 26) {+ return {};}- return { width: readUint32(buffer, 16), height: readUint32(buffer, 20) };+ const colorType = buffer[25];++ return {+ width: readUint32(buffer, 16),+ height: readUint32(buffer, 20),+ bitDepth: buffer[24],+ channels: PNG_CHANNELS[colorType] ?? null,+ // 4 is greyscale with alpha and 6 is colour with alpha; the rest carry none. A palette can+ // still hold transparency in a tRNS chunk, which this deliberately does not go looking for+ // — what matters to a caller is the channel the pixels are stored with.+ hasAlpha: colorType === 4 || colorType === 6,+ indexed: colorType === 3+ };}/**@@ -83,13 +121,13 @@ function readPngDimensions(buffer: Uint8Array): { width: number; height: number* 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 {+function readJpegHeader(buffer: Uint8Array): Partial<ImageMeasurements> {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;+ return {};}const marker = buffer[offset + 1];@@ -109,22 +147,59 @@ function readJpegDimensions(buffer: Uint8Array): { width: number; height: numberconst length = (buffer[offset + 2] << 8) | buffer[offset + 3];if (length < 2 || offset + 2 + length > buffer.length) {- return null;+ return {};}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;+ return readFrameHeader(buffer, offset);}offset += 2 + length;}- return null;+ return {};}+/**+ * The frame header states, in order: bits per sample, height, width, and how many components the+ * image is made of — one for greyscale, three for colour, four for CMYK. A JPEG never carries an+ * alpha channel, whatever else it says.+ */+function readFrameHeader(buffer: Uint8Array, offset: number): Partial<ImageMeasurements> {+ if (offset + 10 > buffer.length) {+ return {};+ }++ return {+ width: (buffer[offset + 7] << 8) | buffer[offset + 8],+ height: (buffer[offset + 5] << 8) | buffer[offset + 6],+ bitDepth: buffer[offset + 4],+ channels: buffer[offset + 9],+ hasAlpha: false,+ indexed: false+ };+}++/** Reads two little-endian 16-bit figures as a size, which is how GIF states its own. */+function readUint16LePair(buffer: Uint8Array, widthOffset: number, heightOffset: number): Partial<ImageMeasurements> {+ return {+ width: buffer[widthOffset] | (buffer[widthOffset + 1] << 8),+ height: buffer[heightOffset] | (buffer[heightOffset + 1] << 8)+ };+}++/** The same in 32 bits, which is how BMP states its own — negative height meaning top-down. */+function readUint32LePair(buffer: Uint8Array, widthOffset: number, heightOffset: number): Partial<ImageMeasurements> {+ const read = (offset: number) => (+ buffer[offset] | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)+ );++ return { width: Math.abs(read(widthOffset)), height: Math.abs(read(heightOffset)) };+}++/** How many channels each PNG colour type stores; a palette index counts as one. */+const PNG_CHANNELS: Record<number, number> = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 };+/*** 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.diff --git a/apps/server/src/services/jpeg_quality.ts b/packages/trilium-core/src/services/jpeg_quality.tssimilarity index 100%rename from apps/server/src/services/jpeg_quality.tsrename to packages/trilium-core/src/services/jpeg_quality.ts