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: update the automatic compression mechanism to use the new implementation
Adorian Doranaaf86711ae3b
diff --git a/apps/server/src/services/image_compression.spec.ts b/apps/server/src/services/image_compression.spec.tsindex ee3b489fa3..670301fdb5 100644--- a/apps/server/src/services/image_compression.spec.ts+++ b/apps/server/src/services/image_compression.spec.ts@@ -1,6 +1,6 @@import type { ImageCompressionResponse } from "@triliumnext/commons";import { becca, cls, getSql, options } from "@triliumnext/core";-import { cancelImageCompression, collectNoteTargets, HEADER_BYTES, writeImage } from "@triliumnext/core/src/services/image_compression.js";+import { automaticCompressionRequest, cancelImageCompression, collectNoteTargets, HEADER_BYTES, writeImage } from "@triliumnext/core/src/services/image_compression.js";import { getImageProvider, initImageProvider } from "@triliumnext/core/src/services/image_provider.js";import { createTextNote } from "@triliumnext/core/src/test/api_fixtures.js";import { CoreApiTester } from "@triliumnext/core/src/test/api_tester.js";@@ -53,12 +53,25 @@ beforeAll(async () => {}, 60000);afterEach(() => {- cls.init(() => {- options.setOption("imageMaxWidthHeight", "2000");- options.setOption("imageJpegQuality", "75");+ setImageOptions({+ imageMaxWidthHeight: "2000",+ imageJpegQuality: "75",+ imageConversionQuality: "75",+ imageResize: "true",+ imageJpegHandling: "compress",+ imagePngHandling: "jpeg"});});+/** Writes image options as the strings they are stored as, valid or otherwise. */+function setImageOptions(values: Record<string, string>) {+ cls.init(() => {+ for (const [ name, value ] of Object.entries(values)) {+ options.setOption(name as Parameters<typeof options.setOption>[0], value);+ }+ });+}+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");@@ -265,6 +278,50 @@ describe("compress note images (POST /api/notes/:noteId/compress-images)", () =>});});+describe("what automatic compression is set to do", () => {+ it("reads the image options as one request, disregarding any value it could not act on", () => {+ setImageOptions({+ imageResize: "false",+ imageMaxWidthHeight: "1280",+ imageJpegHandling: "keep",+ imagePngHandling: "optimize",+ imageJpegQuality: "60",+ imageConversionQuality: "90"+ });++ // Everything the settings page can say, said back — this is what an uploaded image is put+ // through, and the two qualities are separate here as they are everywhere else.+ expect(automaticCompressionRequest()).toEqual({+ resize: false,+ maxWidthHeight: 1280,+ jpegHandling: "keep",+ pngHandling: "optimize",+ quality: 60,+ conversionQuality: 90+ });++ setImageOptions({+ imageMaxWidthHeight: "0",+ imageJpegHandling: "squeeze",+ imagePngHandling: "",+ imageJpegQuality: "500",+ imageConversionQuality: "not a number"+ });++ // None of which throws. A stored setting is not a validated one — it arrives by+ // synchronisation from another instance, or from a database edited by hand — and this is+ // read on the way into an upload, where refusing the settings would mean refusing the+ // image. Each unusable value falls back to what its option ships as.+ expect(automaticCompressionRequest()).toMatchObject({+ maxWidthHeight: 2000,+ jpegHandling: "compress",+ pngHandling: "jpeg",+ quality: 75,+ conversionQuality: 75+ });+ });+});+describe("compression parameters", () => {it("resizes to the requested bound rather than the option's", async () => {const noteId = await createImageNote(noisyPng);diff --git a/apps/server/src/services/image_provider.spec.ts b/apps/server/src/services/image_provider.spec.tsindex fd52ef44a9..1025976bd8 100644--- a/apps/server/src/services/image_provider.spec.ts+++ b/apps/server/src/services/image_provider.spec.ts@@ -103,7 +103,15 @@ beforeAll(async () => {}, 30000);afterEach(() => {- setOptions({ compressImages: 'true', imageJpegQuality: '75', imageMaxWidthHeight: '2000' });+ setOptions({+ compressImages: 'true',+ imageJpegQuality: '75',+ imageConversionQuality: '75',+ imageMaxWidthHeight: '2000',+ imageResize: 'true',+ imageJpegHandling: 'compress',+ imagePngHandling: 'jpeg'+ });});describe('serverImageProvider.getImageType', () => {@@ -139,12 +147,18 @@ describe('serverImageProvider.getImageType', () => {describe('serverImageProvider.processImage', () => {it('returns the original buffer and detected format when compression is disabled', async () => {- setOptions({ compressImages: 'false' });+ // An image that genuinely does compress when the option is on, so what this proves is the+ // switch rather than the image: a picture nothing could shrink comes back untouched either+ // way, and would pass this whether or not the option was ever read.+ setOptions({ compressImages: 'false', imageMaxWidthHeight: '100' });- const result = await serverImageProvider.processImage(smallPng, 'a.png', true);+ const result = await serverImageProvider.processImage(noisyPng, 'a.png', true);- expect(result.buffer).toBe(smallPng);+ expect(result.buffer).toBe(noisyPng);expect(result.format).toEqual({ ext: 'png', mime: 'image/png' });++ setOptions({ compressImages: 'true' });+ expect((await serverImageProvider.processImage(noisyPng, 'a.png', true)).buffer).not.toBe(noisyPng);});it('uses the octet-stream fallback format when the type cannot be detected', async () => {@@ -228,27 +242,55 @@ describe('serverImageProvider.processImage', () => {expect(result.format).toEqual({ ext: 'png', mime: 'image/png' });});- async function shrunkSize(jpegQuality: string): Promise<number> {- setOptions({ imageMaxWidthHeight: '100', imageJpegQuality: jpegQuality });+ /** Shrinks the noisy PNG, which the default handling converts, under the given settings. */+ async function shrunkSize(values: Record<string, string>): Promise<number> {+ setOptions({ imageMaxWidthHeight: '100', ...values });const result = await serverImageProvider.processImage(noisyPng, 'wide.png', true);expect(result.format).toEqual({ ext: 'jpg', mime: 'image/jpeg' });return result.buffer.byteLength;}- it('clamps out-of-range JPEG quality to the default (75)', async () => {+ it('clamps an out-of-range quality to the default (75)', async () => {// An out-of-range quality must produce byte-identical output to an explicit// quality of 75, and differ from a valid in-range quality — proving the clamp// actually ran (and the bad value was not passed through).- const at75 = await shrunkSize('75');- const valid = await shrunkSize('30');- const tooLow = await shrunkSize('5');- const tooHigh = await shrunkSize('150');+ const at75 = await shrunkSize({ imageConversionQuality: '75' });+ const valid = await shrunkSize({ imageConversionQuality: '30' });+ const tooLow = await shrunkSize({ imageConversionQuality: '5' });+ const tooHigh = await shrunkSize({ imageConversionQuality: '150' });expect(tooLow).toBe(at75);expect(tooHigh).toBe(at75);expect(valid).not.toBe(at75);});+ it('writes a PNG it converts at the conversion quality, not the recompression one', async () => {+ // The two were one setting: automatic shrinking wrote every image it touched, whatever it+ // started as, at imageJpegQuality. They are now the same two qualities the tool has —+ // giving up detail a lossless original genuinely holds is a different bet from squeezing+ // an already-lossy one, and the settings say so.+ const at75 = await shrunkSize({ imageConversionQuality: '75', imageJpegQuality: '75' });++ expect(await shrunkSize({ imageConversionQuality: '75', imageJpegQuality: '30' })).toBe(at75);+ expect(await shrunkSize({ imageConversionQuality: '30', imageJpegQuality: '75' })).not.toBe(at75);+ });++ it('honours each handling on the way in, the same choices the tool offers', async () => {+ // "keep" is the setting the automatic path never had: before this, a PNG arriving here+ // could only ever leave as a JPEG.+ setOptions({ imagePngHandling: 'keep', imageMaxWidthHeight: '2000' });+ expect((await serverImageProvider.processImage(noisyPng, 'wide.png', true)).buffer).toBe(noisyPng);++ setOptions({ imagePngHandling: 'optimize' });+ const optimized = await serverImageProvider.processImage(photoPng, 'photo.png', true);+ expect(optimized.format).toEqual({ ext: 'png', mime: 'image/png' });++ // And resizing can be switched off on its own, leaving the re-encodings to do what they can.+ setOptions({ imageResize: 'false', imagePngHandling: 'jpeg', imageMaxWidthHeight: '100' });+ const unresized = await serverImageProvider.processImage(photoPng, 'photo.png', true);+ expect(unresized.format).toEqual({ ext: 'jpg', mime: 'image/jpeg' });+ });+it('bakes EXIF orientation into the pixels when shrinking a rotated photo (#4254)', async () => {setOptions({ compressImages: 'true', imageMaxWidthHeight: '100' });diff --git a/apps/server/src/services/image_provider.ts b/apps/server/src/services/image_provider.tsindex d34dbd55f4..bc8244bdee 100644--- a/apps/server/src/services/image_provider.ts+++ b/apps/server/src/services/image_provider.ts@@ -6,22 +6,18 @@* reads, the logger the codec has no way to reach, and the platform interface core calls through.*/-import { getLog, options as optionService } from "@triliumnext/core";+import { getLog, imageCompressionService, options as optionService } from "@triliumnext/core";import type { ImageCompressionOutcome, ImageCompressionPlan, ImageCompressionRequest, ImageFormat, ImageProvider, ProcessedImage } from "@triliumnext/core/src/services/image_provider.js";-import isAnimated from "is-animated";--import { compressInWorker, compressionConcurrency } from "./image_worker_pool.js";import {- asBuffer,- DECODE_MEMORY_MB,compressImageBytes,+ DECODE_MEMORY_MB,decodeCostOf,- decodeImage,detectSvg,getImageTypeFromBuffer,planFromBytes} from "./image_codec.js";+import { compressInWorker, compressionConcurrency } from "./image_worker_pool.js";/*** Lines the codec produced, written where the rest of the server's logging goes.@@ -37,52 +33,6 @@ const toBackendLog = (message: string, detail?: boolean) => {}};-async function shrinkImage(buffer: Uint8Array, originalName: string): Promise<Uint8Array> {- let jpegQuality = optionService.getOptionInt("imageJpegQuality", 0);-- if (jpegQuality < 10 || jpegQuality > 100) {- jpegQuality = 75;- }-- let finalImageBuffer: Uint8Array;- try {- finalImageBuffer = await resize(buffer, jpegQuality);- } catch (e: unknown) {- const error = e as Error;- getLog().error(`Failed to resize image '${originalName}', stack: ${error.stack}`);- finalImageBuffer = buffer;- }-- // If resizing did not help with size, then save the original- if (finalImageBuffer.byteLength >= buffer.byteLength) {- finalImageBuffer = buffer;- }-- return finalImageBuffer;-}--async function resize(buffer: Uint8Array, quality: number): Promise<Uint8Array> {- const imageMaxWidthHeight = optionService.getOptionInt("imageMaxWidthHeight");-- const start = Date.now();-- const image = await decodeImage(buffer);-- if (image.bitmap.width > image.bitmap.height && image.bitmap.width > imageMaxWidthHeight) {- image.resize({ w: imageMaxWidthHeight });- } else if (image.bitmap.height > imageMaxWidthHeight) {- image.resize({ h: imageMaxWidthHeight });- }-- // When converting PNG to JPG, we lose the alpha channel - replace with white- image.background = 0xffffffff;-- const resultBuffer = await image.getBuffer("image/jpeg", { quality });-- getLog().info(`Resizing image of ${resultBuffer.byteLength} took ${Date.now() - start}ms`);-- return resultBuffer;-}export const serverImageProvider: ImageProvider = {getImageType(buffer: Uint8Array): ImageFormat | null {@@ -92,39 +42,41 @@ export const serverImageProvider: ImageProvider = {return detectSvg(buffer);},+ /**+ * Shrinks an image on its way in, if the settings say so and the image can take it.+ *+ * Two switches have to agree: `compressImages`, which governs every image that arrives, and the+ * caller's own `shrink` — an import the user told not to touch its images passes false, and no+ * setting overrides that.+ *+ * Past them this is {@link compressImage}, the tool's own path, so an uploaded image is put+ * through exactly what the tool would put an existing one through: the same format gates, the+ * same "already re-encoded, leave it" reading, the same worker. What comes back untouched is+ * stored untouched — a skip here is not a failure, it is the answer that this image had nothing+ * to gain, and the original is what should be kept in that case anyway.+ */async processImage(buffer: Uint8Array, originalName: string, shrink: boolean): Promise<ProcessedImage> {- const compressImages = optionService.getOptionBool("compressImages");- const origImageFormat = await getImageTypeFromBuffer(buffer);+ const original = async (): Promise<ProcessedImage> => ({+ buffer,+ format: (await getImageTypeFromBuffer(buffer)) ?? { ext: "dat", mime: "application/octet-stream" }+ });- let shouldShrink = shrink;-- if (!origImageFormat || !["jpg", "png"].includes(origImageFormat.ext)) {- shouldShrink = false;- /* v8 ignore start -- rare defensive guard: spec-compliant animated images are- already excluded above (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 slips through (file-type bails to "png" at its chunk-scan limit while- is-animated still flags it), so this guard correctly skips recompressing it. */- } else if (isAnimated(asBuffer(buffer))) {- // Recompression of animated images would make them static.- shouldShrink = false;+ if (!shrink || !optionService.getOptionBool("compressImages")) {+ return original();}- /* v8 ignore stop */- let finalBuffer: Uint8Array;- let format: ImageFormat;+ try {+ const outcome = await this.compressImage(+ buffer, imageCompressionService.automaticCompressionRequest());- if (compressImages && shouldShrink) {- finalBuffer = await shrinkImage(buffer, originalName);- /* v8 ignore next -- the "jpg" fallback is unreachable: shrinkImage returns- either a detectable JPEG or the (jpg/png-detectable) original buffer. */- format = (await getImageTypeFromBuffer(finalBuffer)) || { ext: "jpg", mime: "image/jpeg" };- } else {- finalBuffer = buffer;- format = origImageFormat || { ext: "dat", mime: "application/octet-stream" };- }+ return outcome.compressed ? { buffer: outcome.buffer, format: outcome.format } : original();+ } catch (e: unknown) {+ // One image that cannot be compressed is still an image the user asked to store. The+ // failure is worth a line, and then the original goes in exactly as it arrived.+ getLog().error(`Failed to compress image '${originalName}': ${(e as Error)?.stack ?? e}`);- return { buffer: finalBuffer, format };+ return original();+ }},async planCompression(header: Uint8Array, request: ImageCompressionRequest): Promise<ImageCompressionPlan> {diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.tsindex 7c85f6b91f..ad194f9a72 100644--- a/packages/commons/src/lib/options_interface.ts+++ b/packages/commons/src/lib/options_interface.ts@@ -1,4 +1,5 @@import type { KeyboardActionNames } from "./keyboard_actions_interface.js";+import type { ImageJpegHandling, ImagePngHandling } from "./server_api.js";/*** A dictionary where the keys are the option keys (e.g. `theme`) and their corresponding values.@@ -121,6 +122,8 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActimonospaceFontSize: number;imageMaxWidthHeight: number;imageJpegQuality: number;+ /** JPEG quality a lossless image is converted at, kept apart from {@link imageJpegQuality}. */+ imageConversionQuality: number;leftPaneWidth: number;rightPaneWidth: number;rightPaneCollapsedItems: string;@@ -183,6 +186,15 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActiweeklyBackupEnabled: boolean;monthlyBackupEnabled: boolean;compressImages: boolean;+ /**+ * Whether an image above {@link imageMaxWidthHeight} is scaled down on its way in. Off, the+ * bound governs nothing and only the re-encoding choices below can shrink anything.+ */+ imageResize: boolean;+ /** What becomes of an already-lossy image on its way in: left as encoded, or recompressed. */+ imageJpegHandling: ImageJpegHandling;+ /** What becomes of a lossless image on its way in: left alone, quantized, or converted. */+ imagePngHandling: ImagePngHandling;downloadImagesAutomatically: boolean;checkForUpdates: boolean;disableTray: boolean;diff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.tsindex 8809d35176..6186af0f0b 100644--- a/packages/trilium-core/src/routes/api/options.ts+++ b/packages/trilium-core/src/routes/api/options.ts@@ -68,6 +68,10 @@ const ALLOWED_OPTIONS = new Set<OptionNames>(["spellCheckLanguageCode","imageMaxWidthHeight","imageJpegQuality",+ "imageResize",+ "imageJpegHandling",+ "imagePngHandling",+ "imageConversionQuality","leftPaneWidth","leftPaneVisible","rightPaneWidth",diff --git a/packages/trilium-core/src/services/image_compression.ts b/packages/trilium-core/src/services/image_compression.tsindex f6cbcc3e99..2742a75c49 100644--- a/packages/trilium-core/src/services/image_compression.ts+++ b/packages/trilium-core/src/services/image_compression.ts@@ -180,11 +180,51 @@ function defaultMaxWidthHeight(): number {const FALLBACK_MAX_WIDTH_HEIGHT = 2000;function defaultQuality(): number {- const configured = optionService.getOptionInt("imageJpegQuality", 0);+ return storedQuality("imageJpegQuality");+}++function storedQuality(name: "imageJpegQuality" | "imageConversionQuality"): number {+ const configured = optionService.getOptionInt(name, 0);return configured >= MIN_QUALITY && configured <= MAX_QUALITY ? configured : DEFAULT_QUALITY;}+/**+ * What automatic shrinking is set to do to an image on its way in — the same request the tool sends,+ * read from the image options instead of from a dialog.+ *+ * This is what puts uploads, pastes and imports on the compression the tool uses: PNGs quantized+ * rather than only ever turned into JPEGs, a JPEG already written at the target quality left alone+ * instead of squeezed again on every upload, and the decode run off-thread where there is a worker+ * for it. Before this, the automatic path had a resizer of its own that did none of that.+ *+ * Read as defensively as the two readers above, and for the same reason: a stored setting is not a+ * validated one. It arrives by synchronisation from another instance, or from a database edited by+ * hand, and a value that cannot be acted on falls back to what the option ships as. Nothing here+ * throws — this runs on the way into an upload, where refusing the settings would mean refusing the+ * image.+ */+export function automaticCompressionRequest(): ImageCompressionRequest {+ return {+ resize: optionService.getOptionBool("imageResize"),+ maxWidthHeight: defaultMaxWidthHeight(),+ jpegHandling: storedHandling("imageJpegHandling", IMAGE_JPEG_HANDLINGS, "compress"),+ pngHandling: storedHandling("imagePngHandling", IMAGE_PNG_HANDLINGS, "jpeg"),+ quality: defaultQuality(),+ conversionQuality: storedQuality("imageConversionQuality")+ };+}++function storedHandling<T extends string>(+ name: "imageJpegHandling" | "imagePngHandling",+ allowed: readonly T[],+ fallback: T+): T {+ const configured = optionService.getOption(name);++ return allowed.includes(configured as T) ? (configured as T) : fallback;+}+/** What an image weighs, and enough of its front to say what it is. */export interface TargetPeek {/** The stored image's size in bytes — the whole of it, not of {@link header}. */@@ -852,6 +892,7 @@ function summarize(items: ImageCompressionItem[]): ImageCompressionResponse {}export default {+ automaticCompressionRequest,compressNoteImages,compressAttachmentImage,cancelImageCompression,diff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.tsindex 772460b039..f174d10054 100644--- a/packages/trilium-core/src/services/options_init.ts+++ b/packages/trilium-core/src/services/options_init.ts@@ -166,6 +166,14 @@ const defaultOptions: DefaultOption[] = [{ name: "spellCheckLanguageCode", value: "en-US", isSynced: false },{ name: "imageMaxWidthHeight", value: "2000", isSynced: true },{ name: "imageJpegQuality", value: "75", isSynced: true },+ // The three below are what automatic compression always did, said out loud rather than left+ // implicit: oversized images scaled down, JPEGs recompressed, PNGs written back as JPEGs. They+ // are defaults for what an install already does, not a recommendation — `optimize` keeps a PNG+ // a PNG, and is the gentler answer for anyone who would rather it did.+ { name: "imageResize", value: "true", isSynced: true },+ { name: "imageJpegHandling", value: "compress", isSynced: true },+ { name: "imagePngHandling", value: "jpeg", isSynced: true },+ { name: "imageConversionQuality", value: "75", isSynced: true },{ name: "autoFixConsistencyIssues", value: "true", isSynced: false },{ name: "vimKeymapEnabled", value: "false", isSynced: false },{ name: "codeLineWrapEnabled", value: "true", isSynced: false },