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 tool: add support for optimizing PNGs
Adorian Doran17a7f48c6388
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex b2322a4ee9..6fb9baf7ca 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2923,7 +2923,9 @@"compress_reencode": "Re-encode lossy images","compress_reencode_help": "Recompresses images that are already lossy, such as JPEG, at the given quality, whatever their size. They lose a little more quality each time, and the loss is permanent. Lossless images, such as PNG, are not affected by this setting.","compress_convert_lossless": "Convert lossless images to lossy",- "compress_convert_lossless_help": "Re-encodes lossless images, such as PNG, as JPEG at the given quality. This usually saves the most space, but the quality loss is permanent and the image stops being lossless. Images with transparency are never converted, as JPEG cannot store it. With this turned off, lossless images keep their format and only resizing can shrink them.",+ "compress_convert_lossless_help": "Re-encodes lossless images, such as PNG, as JPEG at the given quality. This usually saves the most space, but the quality loss is permanent and the image stops being lossless. Images with transparency are never converted, as JPEG cannot store it.",+ "compress_optimize_png": "Reduce colors in PNG images",+ "compress_optimize_png_help": "Shrinks PNG images by reducing them to a palette of 256 colors, keeping them PNG. This is lossy and permanent, although images with few colors, such as screenshots and diagrams, usually look unchanged. Transparency is preserved, so this is the only setting that can shrink a transparent image. It applies to PNGs that stay PNGs: transparent ones, and all of them when converting to lossy is turned off.","compress_process_child_notes": "Process child notes as well","compress_process_child_notes_help": "Compresses the images of every note in the subtree, not just the selected one. Beware that a child note may be a clone, in which case its images are shared with the other notes it appears in.","compress_cancel": "Cancel",diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_dialog.spec.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_dialog.spec.tsxindex 9ac5039760..4fa119ef39 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_dialog.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_dialog.spec.tsx@@ -194,18 +194,22 @@ describe("showImageCompressionDialog", () => {// ones stop being lossless. Neither implies the other."space_usage.compress_reencode","space_usage.compress_convert_lossless",- // Standing on its own rather than under either: every step above writes a JPEG.+ // The third re-encoding choice: shrinking a PNG that is staying a PNG.+ "space_usage.compress_optimize_png",+ // Standing on its own rather than under any of them: the quality governs the steps+ // that write a JPEG, and none of the one that writes a PNG."images.jpeg_quality","space_usage.compress_process_child_notes"]);- expect(rows().map(controlOf)).toEqual([ "toggle", "number", "toggle", "toggle", "slider", "toggle" ]);- expect(rows().map(isNested)).toEqual([ false, true, false, false, false, false ]);+ expect(rows().map(controlOf))+ .toEqual([ "toggle", "number", "toggle", "toggle", "toggle", "slider", "toggle" ]);+ expect(rows().map(isNested)).toEqual([ false, true, false, false, false, false, false ]);// Each switch turns on something with a consequence its label cannot carry — what is left// untouched, a permanent quality loss, a reach past the note the run was invoked on — so// each explains itself beside its title. The two figures say all there is to say already.expect(rows().map((row) => !!row.querySelector(".image-compression-section-title .contextual-help")))- .toEqual([ true, false, true, true, false, true ]);+ .toEqual([ true, false, true, true, true, false, true ]);});it("shows the bound only while there is a step that measures against it", async () => {@@ -226,6 +230,7 @@ describe("showImageCompressionDialog", () => {await toggle(toggles()[0]);await toggle(toggles()[1]);await toggle(toggles()[2]);+ await toggle(toggles()[3]);expect(titles()).toContain("images.jpeg_quality");expect(slider()).not.toBeNull();@@ -239,6 +244,7 @@ describe("showImageCompressionDialog", () => {"images.max_image_dimensions","space_usage.compress_reencode","space_usage.compress_convert_lossless",+ "space_usage.compress_optimize_png","images.jpeg_quality"]);});@@ -248,7 +254,7 @@ describe("showImageCompressionDialog", () => {// A slider says which way it is going but never where it is, so the row reads// title, value, control — the reading placed before the control it reads.- expect(Array.from(rows()[4].children).map((child) => child.classList[0])).toEqual([+ expect(Array.from(rows()[5].children).map((child) => child.classList[0])).toEqual(["image-compression-section-title","image-compression-section-value","slider"@@ -268,10 +274,10 @@ describe("showImageCompressionDialog", () => {expect(numberField()?.value).toBe(String(CONFIGURED_MAX_DIMENSIONS));expect(slider()?.value).toBe(String(CONFIGURED_QUALITY));- // All three steps start on — converting in particular, being where nearly all the saving+ // Every step starts on — converting in particular, being where nearly all the saving// comes from. Reaching into the subtree does not: that widens what the run touches rather// than how hard it compresses, and a descendant may be a clone.- expect(toggles().map((input) => input.checked)).toEqual([ true, true, true, false ]);+ expect(toggles().map((input) => input.checked)).toEqual([ true, true, true, true, false ]);});it("keeps a stored answer of off for a step, rather than reasserting the default", async () => {@@ -279,7 +285,7 @@ describe("showImageCompressionDialog", () => {await openDialog();- expect(toggles().map((input) => input.checked)).toEqual([ true, true, false, false ]);+ expect(toggles().map((input) => input.checked)).toEqual([ true, true, false, true, false ]);});it("reads a stored answer back, and lets it override the image options", async () => {@@ -291,7 +297,7 @@ describe("showImageCompressionDialog", () => {expect(numberField()?.value).toBe("800");expect(slider()?.value).toBe("35");- expect(toggles().map((input) => input.checked)).toEqual([ true, false, true, true ]);+ expect(toggles().map((input) => input.checked)).toEqual([ true, false, true, true, true ]);});it.each([@@ -320,7 +326,7 @@ describe("showImageCompressionDialog", () => {await type(numberField(), "900");await drag(slider(), "45");await toggle(toggles()[1]);- await toggle(toggles()[3]);+ await toggle(toggles()[4]);// The last write carries the whole set, each change having been folded into the one before.expect(mocks.save).toHaveBeenLastCalledWith("imageCompressionToolOptions", JSON.stringify({@@ -328,6 +334,7 @@ describe("showImageCompressionDialog", () => {maxWidthHeight: 900,reencode: false,convertLossless: true,+ optimizePNG: true,quality: 45,processChildNotes: true}));@@ -339,6 +346,7 @@ describe("showImageCompressionDialog", () => {await toggle(toggles()[0]);await toggle(toggles()[1]);await toggle(toggles()[2]);+ await toggle(toggles()[3]);// Every image would be visited and none of them changed; a button that provably does// nothing is not one to offer.@@ -360,7 +368,7 @@ describe("showImageCompressionDialog", () => {it("hands back nothing when the user backs out, settings remembered all the same", async () => {const { closed } = await openDialog();- await toggle(toggles()[3]);+ await toggle(toggles()[4]);await click(cancelButton());// The answer is "no run", and nothing was asked of the server — but the settings are kept@@ -376,7 +384,7 @@ describe("running the compression", () => {it("sends the settings to the note endpoint, the subtree choice among them", async () => {const { closed } = await openDialog();- await toggle(toggles()[3]);+ await toggle(toggles()[4]);await click(compressButton());await closed;@@ -386,6 +394,7 @@ describe("running the compression", () => {maxWidthHeight: CONFIGURED_MAX_DIMENSIONS,reencode: true,convertLossless: true,+ optimizePNG: true,quality: CONFIGURED_QUALITY,recursive: true});@@ -399,7 +408,7 @@ describe("running the compression", () => {await closed;// The server defaults an omitted step to on, so silence would ask for the opposite.- expect(postedBody()).toMatchObject({ resize: false, reencode: true, convertLossless: true });+ expect(postedBody()).toMatchObject({ resize: false, reencode: true, convertLossless: true, optimizePNG: true });});it("sends nothing about subtrees to the attachment endpoint, which has no use for it", async () => {diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_dialog.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_dialog.tsxindex b538929ccf..4f39d3c734 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_dialog.tsx+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_dialog.tsx@@ -24,6 +24,7 @@ import {import {ConvertLosslessSection,JpegQualitySection,+ OptimizePngSection,ProcessChildNotesSection,ReduceResolutionSection,ReencodeImagesSection@@ -135,8 +136,9 @@ function ImageCompressionDialog({ target, onFinished }: {<ReduceResolutionSection {...sectionProps} /><ReencodeImagesSection {...sectionProps} /><ConvertLosslessSection {...sectionProps} />- {/* Not nested under either: every step above writes a JPEG on some image or other,- so the quality is in force whichever of them is on. */}+ <OptimizePngSection {...sectionProps} />+ {/* Not nested under any of them: the quality governs every step that writes a+ JPEG, and none of the step that writes a PNG. */}<JpegQualitySection {...sectionProps} />{/* An attachment is one image; there is no subtree under it to reach into. */}{target.type === "note" && <ProcessChildNotesSection {...sectionProps} />}diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_operation.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_operation.tsindex 30c94b4bae..23fecba187 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_operation.ts+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_operation.ts@@ -37,6 +37,7 @@ export function runImageCompression(maxWidthHeight: options.maxWidthHeight,reencode: options.reencode,convertLossless: options.convertLossless,+ optimizePNG: options.optimizePNG,quality: options.quality,// Left out entirely for an attachment, which has no subtree to descend into — the endpoint// does not read it, and sending it would suggest it does.diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_options.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_options.tsindex d765a40d88..8bf196ef4b 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_options.ts+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_options.ts@@ -16,6 +16,8 @@ export interface ImageCompressionToolOptions {reencode: boolean;/** Whether a lossless image (PNG) may be re-encoded as JPEG. */convertLossless: boolean;+ /** Whether a PNG staying a PNG may be reduced to a palette, transparency and all. */+ optimizePNG: boolean;/** JPEG quality, {@link MIN_QUALITY} to {@link MAX_QUALITY}, whenever the output is a JPEG. */quality: number;/** Whether the note's whole subtree is compressed, rather than the note on its own. */@@ -27,7 +29,7 @@ export interface ImageCompressionToolOptions {* image would be visited and left exactly as it was, so the run is not one worth offering.*/export function hasWorkToDo(options: ImageCompressionToolOptions): boolean {- return options.resize || options.reencode || options.convertLossless;+ return options.resize || options.reencode || options.convertLossless || options.optimizePNG;}/** The bounds the server validates against; the controls here never offer a value it would reject. */@@ -60,6 +62,7 @@ export function readImageCompressionOptions(: defaultMaxWidthHeight(),reencode: stored?.reencode ?? true,convertLossless: stored?.convertLossless ?? true,+ optimizePNG: stored?.optimizePNG ?? true,quality: isQuality(stored?.quality) ? Number(stored?.quality) : defaultQuality(),processChildNotes: stored?.processChildNotes === true};diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_sections.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_sections.tsxindex 2d56a9eccf..b65154c12e 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_sections.tsx+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_sections.tsx@@ -121,6 +121,28 @@ export function ConvertLosslessSection({ options, onChange, disabled }: ImageCom);}+/**+ * Shrinking a PNG in place, by reducing it to a palette rather than by changing what it is.+ *+ * Sits after converting because it is what picks up what converting cannot: transparent images,+ * which are never converted, and every PNG at all when converting is off.+ */+export function OptimizePngSection({ options, onChange, disabled }: ImageCompressionSectionProps) {+ return (+ <CardSection className="image-compression-section">+ <span className="image-compression-section-title">+ {t("space_usage.compress_optimize_png")}+ <ContextualHelp helpMessage={t("space_usage.compress_optimize_png_help")} />+ </span>+ <FormToggle+ disabled={disabled}+ currentValue={options.optimizePNG}+ onChange={(value) => onChange({ optimizePNG: value })}+ />+ </CardSection>+ );+}+/*** The quality any JPEG is written at. A row in its own right rather than a qualifier of the* re-encoding step, because it governs more than that step does: scaling a JPEG has to write onediff --git a/apps/server/package.json b/apps/server/package.jsonindex fed9cb1002..e66970b4ac 100644--- a/apps/server/package.json+++ b/apps/server/package.json@@ -105,6 +105,7 @@"tesseract.js": "7.0.0","time2fa": "1.4.2","tmp": "0.2.7",+ "upng-js": "2.1.0","vite": "8.1.5","yauzl": "3.4.0"}diff --git a/apps/server/src/services/image_compression.spec.ts b/apps/server/src/services/image_compression.spec.tsindex 9a765ef91a..4b0f020e2a 100644--- a/apps/server/src/services/image_compression.spec.ts+++ b/apps/server/src/services/image_compression.spec.ts@@ -24,6 +24,8 @@ let smallPng: Uint8Array;let corruptPng: Uint8Array;/** The same picture stored lossily, for telling the two re-encoding switches apart. */let noisyJpeg: Uint8Array;+/** Half-transparent throughout: the image nothing but PNG optimization can reach. */+let transparentPng: Uint8Array;beforeAll(async () => {api = CoreApiTester.build();@@ -38,6 +40,15 @@ beforeAll(async () => {noisyPng = new Uint8Array(await noisy.getBuffer("image/png"));noisyJpeg = new Uint8Array(await noisy.getBuffer("image/jpeg", { quality: 100 }));+ const translucent = new Jimp({ width: 600, height: 400, color: 0x3366cc80 });+ 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) | 0x80) >>> 0;+ translucent.setPixelColor(color, x, y);+ }+ }+ transparentPng = new Uint8Array(await translucent.getBuffer("image/png"));+const small = new Jimp({ width: 8, height: 8, color: 0x3366ccff });smallPng = new Uint8Array(await small.getBuffer("image/png"));@@ -89,7 +100,7 @@ describe("compress note images (POST /api/notes/:noteId/compress-images)", () =>// Scaling is then the only step that can reach a PNG, and there is nothing oversized to// scale. Recompressing lossy images stays on, and has no business with a PNG.const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {- body: { convertLossless: false }+ body: { convertLossless: false, optimizePNG: false }});expect(res.body.compressedCount).toBe(0);@@ -276,7 +287,8 @@ describe("compression parameters", () => {[ "a non-integer quality", { quality: 75.5 } ],[ "a non-boolean resize", { resize: "yes" } ],[ "a non-boolean reencode", { reencode: "yes" } ],- [ "a non-boolean convertLossless", { convertLossless: "yes" } ]+ [ "a non-boolean convertLossless", { convertLossless: "yes" } ],+ [ "a non-boolean optimizePNG", { optimizePNG: "yes" } ]])("400s on %s", async (_label, body) => {const noteId = await createImageNote(smallPng);@@ -307,7 +319,10 @@ describe("compression parameters", () => {const noteId = await createImageNote(noisyPng);const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {- body: { resize: false, reencode: false, convertLossless: false, maxWidthHeight: 10 }+ body: {+ resize: false, reencode: false, convertLossless: false, optimizePNG: false,+ maxWidthHeight: 10+ }});// Oversized by a long way, and still untouched: with nothing switched on, the bound is@@ -317,8 +332,8 @@ describe("compression parameters", () => {});it.each([- [ "the lossy one", { reencode: true, convertLossless: false }, "jpeg.jpg" ],- [ "the lossless one", { reencode: false, convertLossless: true }, "png.png" ]+ [ "the lossy one", { reencode: true, convertLossless: false, optimizePNG: false }, "jpeg.jpg" ],+ [ "the lossless one", { reencode: false, convertLossless: true, optimizePNG: false }, "png.png" ]])("reaches only its own kind of image with %s switched on", async (_label, body, expected) => {const { noteId } = await createTextNote(api);await addAttachment(noteId, "png.png", noisyPng);@@ -331,6 +346,21 @@ describe("compression parameters", () => {expect(res.body.items.filter((item) => item.compressed).map((item) => item.title)).toEqual([ expected ]);});+ it("shrinks a transparent image, which nothing else in the run can reach", async () => {+ const noteId = await createImageNote(transparentPng);++ const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`);++ // Converting refuses it and there is nothing oversized to scale, so before PNG+ // optimization existed this note could not be made smaller at all.+ expect(res.body.items[0]).toMatchObject({ compressed: true, mime: "image/png" });+ expect(res.body.savedSize).toBeGreaterThan(0);++ const stored = readNote(noteId);+ expect(stored.mime).toBe("image/png");+ expect(stored.size).toBeLessThan(transparentPng.byteLength);+ });+it("re-encodes without scaling when only scaling is switched off", 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 16ab44d951..3c05c514ae 100644--- a/apps/server/src/services/image_provider.spec.ts+++ b/apps/server/src/services/image_provider.spec.ts@@ -239,7 +239,8 @@ describe('serverImageProvider.compressImage', () => {/** Every parameter is explicit, so nothing here depends on the stored options. */function request(overrides: Partial<ImageCompressionRequest> = {}): ImageCompressionRequest {return {- resize: true, maxWidthHeight: 2000, reencode: true, convertLossless: true, quality: 75, ...overrides+ resize: true, maxWidthHeight: 2000, reencode: true, convertLossless: true,+ optimizePNG: true, quality: 75, ...overrides};}@@ -284,9 +285,9 @@ describe('serverImageProvider.compressImage', () => {it('leaves a PNG alone on the lossy switch, which is not about lossless images', async () => {// The switch above recompresses JPEGs; a PNG within the bound is none of its business,- // and rewriting one as a PNG at its own size is lossless and pointless besides.+ // and rewriting one as the same PNG at its own size gains nothing besides.const outcome = await serverImageProvider.compressImage(- noisyPng, request({ convertLossless: false }));+ noisyPng, request({ convertLossless: false, optimizePNG: false }));expect(outcome).toEqual({ compressed: false, reason: 'no-gain' });});@@ -342,24 +343,80 @@ describe('serverImageProvider.compressImage', () => {])('changes nothing about %s when every step is off', async (_label, getBuffer) => {const outcome = await serverImageProvider.compressImage(getBuffer(),- request({ resize: false, reencode: false, convertLossless: false, maxWidthHeight: 10 })+ request({+ resize: false, reencode: false, convertLossless: false, optimizePNG: false,+ maxWidthHeight: 10+ }));expect(outcome).toEqual({ compressed: false, reason: 'no-gain' });});});- describe('transparency', () => {- it('refuses to convert a transparent PNG, which JPEG cannot represent', async () => {+ describe('PNG optimization', () => {+ it('shrinks a transparent PNG in place, keeping both the format and the alpha channel', async () => {+ // The whole point of the step: before it, a transparent image inside the bound could+ // not be reached at all — converting is refused and there is nothing to scale.const outcome = await serverImageProvider.compressImage(transparentPng, request());+ expect(outcome).toMatchObject({ compressed: true, format: { ext: 'png', mime: 'image/png' } });+ if (!outcome.compressed) return;+ expect(outcome.buffer.byteLength).toBeLessThan(transparentPng.byteLength);++ const decoded = await Jimp.read(Buffer.from(outcome.buffer));+ expect([decoded.bitmap.width, decoded.bitmap.height]).toEqual([600, 400]);+ expect(decoded.bitmap.data.some((byte, i) => i % 4 === 3 && byte !== 255)).toBe(true);+ });++ it('shrinks an opaque PNG in place when converting is off', async () => {+ const outcome = await serverImageProvider.compressImage(+ noisyPng, request({ convertLossless: false }));++ expect(outcome).toMatchObject({ compressed: true, format: { ext: 'png', mime: 'image/png' } });+ if (!outcome.compressed) return;+ expect(outcome.buffer.byteLength).toBeLessThan(noisyPng.byteLength);+ });++ it('leaves converting to do an opaque PNG, the two never competing over one image', async () => {+ // Both switched on: converting wins for an opaque image, being the larger saving, so+ // quantizing never runs on something that is on its way to being a JPEG.+ const outcome = await serverImageProvider.compressImage(noisyPng, request());++ expect(outcome).toMatchObject({ compressed: true, format: { ext: 'jpg', mime: 'image/jpeg' } });+ });++ it('does not reach a JPEG, which is not a PNG to optimize', async () => {+ const outcome = await serverImageProvider.compressImage(+ noisyJpeg, request({ reencode: false, convertLossless: false }));++ expect(outcome).toEqual({ compressed: false, reason: 'no-gain' });+ });++ it('scales and then quantizes, so both steps land on the stored image', async () => {+ const outcome = await serverImageProvider.compressImage(+ transparentPng, 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]);+ expect(decoded.bitmap.data.some((byte, i) => i % 4 === 3 && byte !== 255)).toBe(true);+ });+ });++ describe('transparency', () => {+ it('refuses to convert a transparent PNG, and says so when nothing else can reach it', async () => {+ const outcome = await serverImageProvider.compressImage(+ transparentPng, request({ optimizePNG: false }));+expect(outcome).toEqual({ compressed: false, reason: 'transparent' });});- it('still scales a transparent PNG down, keeping both the format and the alpha channel', async () => {+ it('still scales a transparent PNG down with nothing else switched on', async () => {const outcome = await serverImageProvider.compressImage(transparentPng,- request({ maxWidthHeight: 100 })+ request({ maxWidthHeight: 100, optimizePNG: false }));expect(outcome).toMatchObject({ compressed: true, format: { ext: 'png', mime: 'image/png' } });diff --git a/apps/server/src/services/image_provider.ts b/apps/server/src/services/image_provider.tsindex 2b19eb62dc..5702944639 100644--- a/apps/server/src/services/image_provider.ts+++ b/apps/server/src/services/image_provider.ts@@ -9,6 +9,7 @@ import imageType from "image-type";import isAnimated from "is-animated";import isSvg from "is-svg";import { Jimp } from "jimp";+import * as UPNG from "upng-js";const JPEG_FORMAT: ImageFormat = { ext: "jpg", mime: "image/jpeg" };const PNG_FORMAT: ImageFormat = { ext: "png", mime: "image/png" };@@ -16,6 +17,18 @@ 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" ]);+/**+ * How large a palette the PNG quantizer may keep — deliberately the largest an indexed PNG can+ * hold, which makes this the gentlest lossy setting there is while still doing the work.+ *+ * The saving comes from storing one index per pixel rather than 24-bit colour, so a screenshot or+ * a diagram — what most PNGs in a note actually are — typically loses half its weight or better+ * with nothing visible to show for it. Going lower (64, 128) starts to band across gradients, and+ * encoding losslessly instead (0) rarely reaches a fifth. Neither extreme is the trade this tool+ * is for.+ */+const PNG_PALETTE_COLORS = 256;+async function getImageTypeFromBuffer(buffer: Uint8Array): Promise<ImageFormat | null> {// Check for SVG first (text-based)if (isSvg(Buffer.from(buffer).toString())) {@@ -153,17 +166,22 @@ export const serverImageProvider: ImageProvider = {// from the header.const toJpeg = !isLossless || (request.convertLossless && !hasTransparency(image));- // Whether re-encoding alone is worth doing to *this* image, which the two switches answer- // for their own kind: a lossy source is recompressed if `reencode` says so, a lossless one- // is worth rewriting only when it is becoming a JPEG — rewriting a PNG as a PNG at its own- // size is lossless and gains nothing.- const worthReencoding = isLossless ? toJpeg : request.reencode;+ // Quantizing applies to a PNG that is staying one — a transparent image, or any of them+ // when converting is off. An opaque PNG being converted goes to JPEG instead, that being+ // the larger saving of the two, so the two steps never compete over the same image.+ const quantize = isLossless && !toJpeg && request.optimizePNG;++ // Whether re-encoding alone is worth doing to *this* image, which each switch answers for+ // its own kind: a lossy source is recompressed if `reencode` says so, a lossless one when+ // it is either becoming a JPEG or being quantized — rewriting a PNG as the same PNG at its+ // own size is lossless and gains nothing.+ const worthReencoding = isLossless ? (toJpeg || quantize) : request.reencode;if (!needsResize && !worthReencoding) {return {compressed: false,- // Transparency is the reason only when converting was actually asked for;- // otherwise there was simply nothing this run wanted to do to the image.+ // Transparency is the reason only when converting was asked for and quantizing was+ // not; otherwise there was simply nothing this run wanted to do to the image.reason: isLossless && request.convertLossless ? "transparent" : "no-gain"};}@@ -183,6 +201,8 @@ export const serverImageProvider: ImageProvider = {// to lose, or by a JPEG source, which never had any to begin with.image.background = 0xffffffff;result = await image.getBuffer("image/jpeg", { quality: request.quality });+ } else if (quantize) {+ result = quantizePng(image, buffer.byteLength);} else {result = await image.getBuffer("image/png");}@@ -198,6 +218,32 @@ export const serverImageProvider: ImageProvider = {}};+/**+ * Rewrites the image as a palette PNG, which is where a PNG's weight actually goes: the saving+ * comes from storing an index per pixel instead of 24-bit colour, not from discarding detail. The+ * alpha channel survives it, so this is the only step that can shrink a transparent image at all.+ *+ * @param originalByteLength the source file, for the ratio in the log line. After a resize the two+ * are not measuring the same picture, which is the reading that matters+ * anyway — how much smaller the stored image ends up.+ */+function quantizePng(image: Awaited<ReturnType<typeof Jimp.read>>, originalByteLength: number): Uint8Array {+ const start = Date.now();+ const { width, height, data } = image.bitmap;+ // A tightly packed copy: UPNG reads the whole ArrayBuffer, so a view carrying a byte offset or+ // slack past the pixels would be read as image data.+ const rgba = new Uint8Array(data);+ const encoded = new Uint8Array(UPNG.encode([ rgba.buffer ], width, height, PNG_PALETTE_COLORS));+ const saved = Math.round((1 - encoded.byteLength / originalByteLength) * 100);++ getLog().info(+ `PNG optimization of ${width}x${height} to ${PNG_PALETTE_COLORS} colors: `+ + `${originalByteLength} -> ${encoded.byteLength} bytes (${saved}% smaller) in ${Date.now() - start}ms`+ );++ return encoded;+}+/** 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;diff --git a/apps/server/src/types-upng-js.d.ts b/apps/server/src/types-upng-js.d.tsnew file mode 100644index 0000000000..1ff80898bc--- /dev/null+++ b/apps/server/src/types-upng-js.d.ts@@ -0,0 +1,30 @@+/**+ * Minimal declarations for `upng-js`, which ships none of its own.+ *+ * Only the encoder is declared, that being all this codebase uses: Jimp already decodes and+ * resizes, and UPNG is reached for solely to write the PNG back out (see `image_provider.ts`).+ * Add to this if a decoding path ever needs it.+ */+declare module "upng-js" {++ /**+ * Encodes RGBA frames as a PNG.+ *+ * @param frames one tightly-packed RGBA8 `ArrayBuffer` per frame; a single-entry array for a+ * still image, more than one producing an APNG.+ * @param width in pixels.+ * @param height in pixels.+ * @param colors size of the palette to quantize to, 1 to 256. **Zero encodes losslessly**,+ * keeping every colour and saving only what a better deflate can.+ * @param delays per-frame delays in milliseconds; APNG only.+ * @returns the encoded PNG.+ */+ export function encode(+ frames: ArrayBuffer[],+ width: number,+ height: number,+ colors: number,+ delays?: number[]+ ): ArrayBuffer;++}diff --git a/apps/standalone/src/services/image_provider.spec.ts b/apps/standalone/src/services/image_provider.spec.tsindex 16227aa21c..8d02a3de8c 100644--- a/apps/standalone/src/services/image_provider.spec.ts+++ b/apps/standalone/src/services/image_provider.spec.ts@@ -85,7 +85,8 @@ describe("standaloneImageProvider.compressImage", () => {await expect(standaloneImageProvider.compressImage(buffer, {- resize: true, maxWidthHeight: 100, reencode: true, convertLossless: true, quality: 75+ resize: true, maxWidthHeight: 100, reencode: true, convertLossless: true,+ optimizePNG: true, quality: 75})).resolves.toEqual({ compressed: false, reason: "unsupported-platform" });});diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex 7ea63ec04a..0655f8968f 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -317,10 +317,23 @@ export interface ImageCompressionOptions {* image the file is, permanently.** A PNG carrying transparency is never converted whatever this says, JPEG having no alpha- * channel to keep it in. With it off, a lossless image stays lossless, so scaling is the only- * thing that can happen to it at all.+ * channel to keep it in — {@link optimizePNG} is what reaches those.*/convertLossless?: boolean;+ /**+ * Whether a PNG that is staying a PNG may be shrunk in place, by reducing it to a palette+ * rather than by changing what it is. It keeps the alpha channel, so it is the only step that+ * reaches a transparent image at all, and the only one that helps a PNG when+ * {@link convertLossless} is off.+ *+ * Lossy, but gently so: the saving comes from dropping 24-bit colour for an index rather than+ * from throwing detail away, which is why it is not governed by {@link quality} — that is the+ * JPEG encoder's knob, and this never produces a JPEG.+ *+ * Applies only where the image is not being converted: an opaque PNG with converting on+ * becomes a JPEG instead, that being the larger saving of the two.+ */+ optimizePNG?: boolean;/*** JPEG quality, 10 to 100. Omitted, it falls back to the `imageJpegQuality` option (75 by* default).@@ -352,7 +365,10 @@ export type ImageCompressionSkipReason =| "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 nothing to scale besides. */+ /**+ * A PNG carrying transparency, which JPEG cannot represent, with neither PNG optimization+ * asked for nor anything to scale — so nothing was left that could reach it.+ */| "transparent"/** The rendered picture of a canvas/mermaid/mind map/spreadsheet note, regenerated on save. */| "generated"diff --git a/packages/trilium-core/src/services/image_compression.ts b/packages/trilium-core/src/services/image_compression.tsindex 7c89510bad..00f75ce645 100644--- a/packages/trilium-core/src/services/image_compression.ts+++ b/packages/trilium-core/src/services/image_compression.ts@@ -62,7 +62,7 @@ export async function compressAttachmentImage(attachmentId: string, options?: Im* failing the request — the caller did not choose that value and cannot fix it from here.*/export function resolveCompressionRequest(options: ImageCompressionOptions = {}): ImageCompressionRequest {- const { resize, maxWidthHeight, reencode, convertLossless, quality } = options;+ const { resize, maxWidthHeight, reencode, convertLossless, optimizePNG, quality } = 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.`);@@ -75,14 +75,16 @@ export function resolveCompressionRequest(options: ImageCompressionOptions = {})requireBoolean(resize, "resize");requireBoolean(reencode, "reencode");requireBoolean(convertLossless, "convertLossless");+ requireBoolean(optimizePNG, "optimizePNG");return {- // All three default on: a request that named none of them asked for the images to be+ // Every step defaults on: a request that named none of them asked for the images to be// compressed, and switching one off is what narrows that down.resize: resize ?? true,maxWidthHeight: maxWidthHeight ?? optionService.getOptionInt("imageMaxWidthHeight"),reencode: reencode ?? true,convertLossless: convertLossless ?? true,+ optimizePNG: optimizePNG ?? true,quality: quality ?? defaultQuality()};}diff --git a/packages/trilium-core/src/services/image_provider.ts b/packages/trilium-core/src/services/image_provider.tsindex d1b3748394..dede4f68ba 100644--- a/packages/trilium-core/src/services/image_provider.ts+++ b/packages/trilium-core/src/services/image_provider.ts@@ -29,6 +29,8 @@ export interface ImageCompressionRequest {reencode: boolean;/** Whether a lossless image (PNG) may be re-encoded as JPEG. */convertLossless: boolean;+ /** Whether a PNG staying a PNG may be reduced to a palette, transparency and all. */+ optimizePNG: boolean;/** JPEG quality, 10 to 100, applied whenever the output is a JPEG. */quality: number;}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 86e097ae6b..845cd82058 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -818,6 +818,9 @@ importers:tmp:specifier: 0.2.7version: 0.2.7+ upng-js:+ specifier: 2.1.0+ version: 2.1.0vite:specifier: 8.1.5version: 8.1.5(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])@@ -12678,6 +12681,9 @@ packages:resolution: {integrity: sha512-+dwUY4L35XFYEzE+OAL3sarJdUioVovq+8f7lcIJ7wnmnYQV5UD1Y/lcwaMSyaQ6Bj3JMj1XSTjZbNLHn/19yA==}engines: {node: '>=18'}+ resolution: {integrity: sha512-d3xzZzpMP64YkjP5pr8gNyvBt7dLk/uGI67EctzDuVp4lCZyVMo0aJO6l/VDlgbInJYDY6cnClLoBp29eKWI6g==}+resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==}@@ -26991,6 +26997,10 @@ snapshots:semver: 7.8.5xdg-basedir: 5.1.0+ dependencies:+ pako: 1.0.11+dependencies:punycode: 2.3.1