Skip to content

Build your personal knowledge base with Trilium Notes

client/image compression tool: make re-encoding optional

Adorian Doranc711abc7d330
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 8ad73174d1..b2322a4ee9 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2918,8 +2918,12 @@
"cleanup_compact_notice": "This operation may take several minutes and Trilium will not respond until it completes.",
"compress_title": "Compress images",
"compress_quality_value": "{{quality}}%",
+ "compress_reduce_resolution": "Reduce image resolution",
+ "compress_reduce_resolution_help": "Scales down images that are larger than the given size, keeping their proportions. Images that already fit are left untouched, so on its own this reaches only oversized images.",
+ "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. This usually saves the most space, but the quality loss is permanent. Images with transparency are left as they are, since JPEG cannot store it.",
+ "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_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.tsx
index 7dd6ed2efa..9ac5039760 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
@@ -184,31 +184,62 @@ afterEach(() => {
});
describe("showImageCompressionDialog", () => {
- it("lists the four settings, in reading order", async () => {
+ it("leads with each step, the bound nested under the one that measures against it", async () => {
await openDialog();
expect(titles()).toEqual([
+ "space_usage.compress_reduce_resolution",
"images.max_image_dimensions",
- "images.jpeg_quality",
+ // One switch per kind of image: recompressing the lossy ones, and letting the lossless
+ // 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.
+ "images.jpeg_quality",
"space_usage.compress_process_child_notes"
]);
- expect(rows().map(controlOf)).toEqual([ "number", "slider", "toggle", "toggle" ]);
+ expect(rows().map(controlOf)).toEqual([ "toggle", "number", "toggle", "toggle", "slider", "toggle" ]);
+ expect(rows().map(isNested)).toEqual([ false, true, false, false, false, false ]);
- // Both toggles turn on something with a consequence their label cannot carry — a permanent
- // quality loss, and a reach past the note the run was invoked on — so each explains itself
- // beside its title. The two numbered rows say all there is to say in their labels.
+ // 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([ false, false, true, true ]);
+ .toEqual([ true, false, true, true, false, true ]);
+ });
+
+ it("shows the bound only while there is a step that measures against it", async () => {
+ await openDialog();
+
+ // Reading it off a switch that is off would present a figure still in force.
+ await toggle(toggles()[0]);
+ expect(titles()).not.toContain("images.max_image_dimensions");
+ expect(numberField()).toBeNull();
+
+ await toggle(toggles()[0]);
+ expect(numberField()?.value).toBe(String(CONFIGURED_MAX_DIMENSIONS));
+ });
+
+ it("keeps the quality up whichever steps are on, being in force for all of them", async () => {
+ await openDialog();
+
+ await toggle(toggles()[0]);
+ await toggle(toggles()[1]);
+ await toggle(toggles()[2]);
+
+ expect(titles()).toContain("images.jpeg_quality");
+ expect(slider()).not.toBeNull();
});
it("drops the subtree row for an attachment, which has no subtree to reach into", async () => {
await openDialog(ATTACHMENT_TARGET);
expect(titles()).toEqual([
+ "space_usage.compress_reduce_resolution",
"images.max_image_dimensions",
- "images.jpeg_quality",
- "space_usage.compress_convert_lossless"
+ "space_usage.compress_reencode",
+ "space_usage.compress_convert_lossless",
+ "images.jpeg_quality"
]);
});
@@ -217,7 +248,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()[1].children).map((child) => child.classList[0])).toEqual([
+ expect(Array.from(rows()[4].children).map((child) => child.classList[0])).toEqual([
"image-compression-section-title",
"image-compression-section-value",
"slider"
@@ -237,30 +268,30 @@ describe("showImageCompressionDialog", () => {
expect(numberField()?.value).toBe(String(CONFIGURED_MAX_DIMENSIONS));
expect(slider()?.value).toBe(String(CONFIGURED_QUALITY));
- // Converting starts on — it is where nearly all the saving comes from, and someone reaching
- // for this tool is already accepting a loss of quality. Reaching into the subtree does not:
- // that widens what the run touches, and a descendant may be a clone.
- expect(toggles().map((input) => input.checked)).toEqual([ true, false ]);
+ // All three steps start 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 ]);
});
- it("keeps a stored answer of off for converting, rather than reasserting the default", async () => {
+ it("keeps a stored answer of off for a step, rather than reasserting the default", async () => {
mocks.storedOption = JSON.stringify({ convertLossless: false });
await openDialog();
- expect(toggles()[0].checked).toBe(false);
+ expect(toggles().map((input) => input.checked)).toEqual([ true, true, false, false ]);
});
it("reads a stored answer back, and lets it override the image options", async () => {
mocks.storedOption = JSON.stringify({
- maxWidthHeight: 800, quality: 35, convertLossless: true, processChildNotes: true
+ maxWidthHeight: 800, quality: 35, reencode: false, processChildNotes: true
});
await openDialog();
expect(numberField()?.value).toBe("800");
expect(slider()?.value).toBe("35");
- expect(toggles().map((input) => input.checked)).toEqual([ true, true ]);
+ expect(toggles().map((input) => input.checked)).toEqual([ true, false, true, true ]);
});
it.each([
@@ -288,18 +319,36 @@ describe("showImageCompressionDialog", () => {
await type(numberField(), "900");
await drag(slider(), "45");
- await toggle(toggles()[0]);
await toggle(toggles()[1]);
+ await toggle(toggles()[3]);
// The last write carries the whole set, each change having been folded into the one before.
expect(mocks.save).toHaveBeenLastCalledWith("imageCompressionToolOptions", JSON.stringify({
+ resize: true,
maxWidthHeight: 900,
+ reencode: false,
+ convertLossless: true,
quality: 45,
- convertLossless: false,
processChildNotes: true
}));
});
+ it("offers no run at all once every step is switched off", async () => {
+ await openDialog();
+
+ await toggle(toggles()[0]);
+ await toggle(toggles()[1]);
+ await toggle(toggles()[2]);
+
+ // Every image would be visited and none of them changed; a button that provably does
+ // nothing is not one to offer.
+ expect(compressButton()?.disabled).toBe(true);
+
+ // Any one of them is enough to make the run worth offering again.
+ await toggle(toggles()[1]);
+ expect(compressButton()?.disabled).toBe(false);
+ });
+
it("holds the dimension to at least one pixel, which is the least the server accepts", async () => {
await openDialog();
@@ -311,7 +360,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()[1]);
+ await toggle(toggles()[3]);
await click(cancelButton());
// The answer is "no run", and nothing was asked of the server — but the settings are kept
@@ -327,19 +376,32 @@ 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()[1]);
+ await toggle(toggles()[3]);
await click(compressButton());
await closed;
expect(postedUrl()).toBe("notes/n1/compress-images");
expect(postedBody()).toEqual({
+ resize: true,
maxWidthHeight: CONFIGURED_MAX_DIMENSIONS,
- quality: CONFIGURED_QUALITY,
+ reencode: true,
convertLossless: true,
+ quality: CONFIGURED_QUALITY,
recursive: true
});
});
+ it("sends a step that was switched off as switched off, rather than leaving it out", async () => {
+ const { closed } = await openDialog();
+
+ await toggle(toggles()[0]);
+ await click(compressButton());
+ 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 });
+ });
+
it("sends nothing about subtrees to the attachment endpoint, which has no use for it", async () => {
const { closed } = await openDialog(ATTACHMENT_TARGET);
@@ -416,6 +478,11 @@ describe("running the compression", () => {
});
});
+/** Whether a row is drawn as qualifying the one above it rather than standing beside it. */
+function isNested(row: HTMLElement) {
+ return row.classList.contains("image-compression-section-nested");
+}
+
/** Which control a row carries, standing in for the setting it configures. */
function controlOf(row: HTMLElement) {
if (row.querySelector(".image-compression-section-number")) {
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.tsx
index 18be0ef47e..b538929ccf 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
@@ -17,14 +17,16 @@ import {
runImageCompression
} from "./image_compression_operation";
import {
+ hasWorkToDo,
type ImageCompressionToolOptions,
readImageCompressionOptions
} from "./image_compression_options";
import {
ConvertLosslessSection,
JpegQualitySection,
- MaxImageDimensionsSection,
- ProcessChildNotesSection
+ ProcessChildNotesSection,
+ ReduceResolutionSection,
+ ReencodeImagesSection
} from "./image_compression_sections";
/**
@@ -118,6 +120,9 @@ function ImageCompressionDialog({ target, onFinished }: {
<Button
text={t("space_usage.compress_run")}
kind="primary"
+ // Neither step switched on would visit every image and change none of them:
+ // a run that provably does nothing is not one to offer.
+ disabled={!hasWorkToDo(options)}
onClick={() => {
pending.current = options;
setShown(false);
@@ -127,9 +132,12 @@ function ImageCompressionDialog({ target, onFinished }: {
stackable
>
<Card className="image-compression-settings">
- <MaxImageDimensionsSection {...sectionProps} />
- <JpegQualitySection {...sectionProps} />
+ <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. */}
+ <JpegQualitySection {...sectionProps} />
{/* An attachment is one image; there is no subtree under it to reach into. */}
{target.type === "note" && <ProcessChildNotesSection {...sectionProps} />}
</Card>
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.ts
index 508d835e02..30c94b4bae 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
@@ -33,9 +33,11 @@ export function runImageCompression(
: `attachments/${target.attachmentId}/compress-image`;
return server.postWithTimeout<ImageCompressionResponse>(url, COMPRESSION_TIMEOUT_MS, {
+ resize: options.resize,
maxWidthHeight: options.maxWidthHeight,
- quality: options.quality,
+ reencode: options.reencode,
convertLossless: options.convertLossless,
+ 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.
...(target.type === "note" ? { recursive: options.processChildNotes } : {})
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.ts
index 49317c7c67..d765a40d88 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
@@ -8,16 +8,28 @@ import optionService from "../../../../../services/options";
* tool's own, the endpoint acting on one note at a time.
*/
export interface ImageCompressionToolOptions {
- /** Longest edge in pixels: a larger image is scaled down to fit, a smaller one left alone. */
+ /** Whether an image larger than {@link maxWidthHeight} is scaled down to fit. */
+ resize: boolean;
+ /** Longest edge in pixels. Only consulted when {@link resize} is on. */
maxWidthHeight: number;
- /** JPEG quality, {@link MIN_QUALITY} to {@link MAX_QUALITY}. */
- quality: number;
- /** Whether a lossless source (PNG) may be re-encoded as JPEG. */
+ /** Whether an already-lossy image (JPEG) is recompressed even when nothing needs scaling. */
+ reencode: boolean;
+ /** Whether a lossless image (PNG) may be re-encoded as JPEG. */
convertLossless: 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. */
processChildNotes: boolean;
}
+/**
+ * Whether the settings amount to anything at all. With none of the three steps switched on, every
+ * 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;
+}
+
/** The bounds the server validates against; the controls here never offer a value it would reject. */
export const MIN_QUALITY = 10;
export const MAX_QUALITY = 100;
@@ -32,21 +44,23 @@ export const MIN_MAX_WIDTH_HEIGHT = 1;
* that has never been run opens on what automatic compression is already configured to do — the same
* fallbacks the server applies to a request that omits them.
*
- * Converting starts on: someone reaching for this tool has a note that has grown too heavy and is
- * already accepting a loss of quality to shrink it, and converting is where nearly all the saving
- * comes from — offering it off by default would mean most first runs reporting almost nothing.
- * 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 shared with notes the user did not have in mind.
+ * All three steps start on, matching the server's own defaults. Converting in particular has to: it
+ * is where nearly all the saving comes from, and with it off a note full of PNGs already inside the
+ * bound would report almost nothing. Reaching into the subtree does not start on: that widens what
+ * the run touches rather than how hard it compresses, and a descendant may be a clone shared with
+ * notes the user did not have in mind.
*/
export function readImageCompressionOptions(
stored: Partial<ImageCompressionToolOptions> | null | undefined
): ImageCompressionToolOptions {
return {
+ resize: stored?.resize ?? true,
maxWidthHeight: isPositiveInteger(stored?.maxWidthHeight)
? Number(stored?.maxWidthHeight)
: defaultMaxWidthHeight(),
- quality: isQuality(stored?.quality) ? Number(stored?.quality) : defaultQuality(),
+ reencode: stored?.reencode ?? true,
convertLossless: stored?.convertLossless ?? 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.css b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_sections.css
index c27768df28..1676c26cc3 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_sections.css
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_sections.css
@@ -43,3 +43,9 @@
flex: 0 0 auto;
}
}
+
+/* Indented by the card itself; quieting the title is what marks it as qualifying the row above
+ rather than standing beside it. */
+.image-compression-section-nested .image-compression-section-title {
+ color: var(--muted-text-color);
+}
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.tsx
index 5de5a6c0bc..2d56a9eccf 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
@@ -19,6 +19,10 @@ import {
* the ones that mean anything where it stands: the compression dialog drops the subtree row for an
* attachment, which has no subtree, and the cleanup tool will drop it too, being database-wide.
*
+ * A figure is nested under a switch only where it qualifies that switch alone — the bound under
+ * scaling, which is the only step that measures against it. The JPEG quality stands on its own,
+ * being in force for every step that writes a JPEG, which is all of them.
+ *
* Every row takes the whole settings object and reports a patch, rather than a value and a setter,
* so a host wires the group once and adding a row later costs it nothing.
*/
@@ -29,10 +33,37 @@ export interface ImageCompressionSectionProps {
disabled?: boolean;
}
+/**
+ * Scaling oversized images down, with the bound they are scaled to. The bound appears only while
+ * the step is on: with it off nothing is measured against it, so a figure sitting there would read
+ * as one still in force.
+ */
+export function ReduceResolutionSection(props: ImageCompressionSectionProps) {
+ const { options, onChange, disabled } = props;
+
+ return (
+ <CardSection
+ className="image-compression-section"
+ subSectionsVisible={options.resize}
+ subSections={[ <MaxImageDimensionsSection key="max-dimensions" {...props} /> ]}
+ >
+ <span className="image-compression-section-title">
+ {t("space_usage.compress_reduce_resolution")}
+ <ContextualHelp helpMessage={t("space_usage.compress_reduce_resolution_help")} />
+ </span>
+ <FormToggle
+ disabled={disabled}
+ currentValue={options.resize}
+ onChange={(value) => onChange({ resize: value })}
+ />
+ </CardSection>
+ );
+}
+
/** The bound images are scaled down to fit. Labelled as the image settings label it. */
export function MaxImageDimensionsSection({ options, onChange, disabled }: ImageCompressionSectionProps) {
return (
- <CardSection className="image-compression-section">
+ <CardSection className="image-compression-section image-compression-section-nested">
<span className="image-compression-section-title">{t("images.max_image_dimensions")}</span>
<FormTextBoxWithUnit
className="image-compression-section-number"
@@ -50,28 +81,30 @@ export function MaxImageDimensionsSection({ options, onChange, disabled }: Image
}
/**
- * The quality re-encoded images are written at. The figure sits between the title and the slider
- * rather than inside the title: a slider says which way it is going but never where it is, and the
- * reading belongs beside the control it reads.
+ * Recompressing images that are already lossy, at whatever {@link JpegQualitySection} is set to.
+ * Says nothing about lossless ones — that is {@link ConvertLosslessSection}'s to answer.
*/
-export function JpegQualitySection({ options, onChange, disabled }: ImageCompressionSectionProps) {
+export function ReencodeImagesSection({ options, onChange, disabled }: ImageCompressionSectionProps) {
return (
<CardSection className="image-compression-section">
- <span className="image-compression-section-title">{t("images.jpeg_quality")}</span>
- <span className="image-compression-section-value">{t("space_usage.compress_quality_value", { quality: options.quality })}</span>
- <Slider
- min={MIN_QUALITY}
- max={MAX_QUALITY}
- step={QUALITY_STEP}
+ <span className="image-compression-section-title">
+ {t("space_usage.compress_reencode")}
+ <ContextualHelp helpMessage={t("space_usage.compress_reencode_help")} />
+ </span>
+ <FormToggle
disabled={disabled}
- value={options.quality}
- onChange={(value) => onChange({ quality: value })}
+ currentValue={options.reencode}
+ onChange={(value) => onChange({ reencode: value })}
/>
</CardSection>
);
}
-/** Whether PNGs may be re-encoded as JPEG — the choice that actually costs quality. */
+/**
+ * Letting lossless images be re-encoded as lossy ones. A choice of its own rather than part of the
+ * row above: squeezing the JPEGs harder is no reason to stop a PNG being a PNG, and this is the one
+ * step that changes what kind of image a file is.
+ */
export function ConvertLosslessSection({ options, onChange, disabled }: ImageCompressionSectionProps) {
return (
<CardSection className="image-compression-section">
@@ -88,6 +121,31 @@ export function ConvertLosslessSection({ options, onChange, disabled }: ImageCom
);
}
+/**
+ * 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 one
+ * back whether or not re-encoding was asked for, so the quality is in force there too.
+ *
+ * The figure sits between the title and the slider rather than inside the title: a slider says
+ * which way it is going but never where it is, and the reading belongs beside the control it reads.
+ */
+export function JpegQualitySection({ options, onChange, disabled }: ImageCompressionSectionProps) {
+ return (
+ <CardSection className="image-compression-section">
+ <span className="image-compression-section-title">{t("images.jpeg_quality")}</span>
+ <span className="image-compression-section-value">{t("space_usage.compress_quality_value", { quality: options.quality })}</span>
+ <Slider
+ min={MIN_QUALITY}
+ max={MAX_QUALITY}
+ step={QUALITY_STEP}
+ disabled={disabled}
+ value={options.quality}
+ onChange={(value) => onChange({ quality: value })}
+ />
+ </CardSection>
+ );
+}
+
/** Whether the run reaches past the note it was invoked on, into its whole subtree. */
export function ProcessChildNotesSection({ options, onChange, disabled }: ImageCompressionSectionProps) {
return (
diff --git a/apps/server/src/services/image_compression.spec.ts b/apps/server/src/services/image_compression.spec.ts
index 5cb4caa28c..9a765ef91a 100644
--- a/apps/server/src/services/image_compression.spec.ts
+++ b/apps/server/src/services/image_compression.spec.ts
@@ -22,6 +22,8 @@ let noisyPng: Uint8Array;
let smallPng: Uint8Array;
/** A PNG signature followed by garbage: passes format detection, fails to decode. */
let corruptPng: Uint8Array;
+/** The same picture stored lossily, for telling the two re-encoding switches apart. */
+let noisyJpeg: Uint8Array;
beforeAll(async () => {
api = CoreApiTester.build();
@@ -34,6 +36,7 @@ beforeAll(async () => {
}
}
noisyPng = new Uint8Array(await noisy.getBuffer("image/png"));
+ noisyJpeg = new Uint8Array(await noisy.getBuffer("image/jpeg", { quality: 100 }));
const small = new Jimp({ width: 8, height: 8, color: 0x3366ccff });
smallPng = new Uint8Array(await small.getBuffer("image/png"));
@@ -80,10 +83,14 @@ describe("compress note images (POST /api/notes/:noteId/compress-images)", () =>
expect(stored.size).toBeLessThan(noisyPng.byteLength);
});
- it("leaves a lossless image note untouched unless conversion is asked for", async () => {
+ it("leaves a PNG within the bound untouched once converting is switched off", async () => {
const noteId = await createImageNote(noisyPng);
- const res = await api.post<ImageCompressionResponse>(`/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 }
+ });
expect(res.body.compressedCount).toBe(0);
expect(res.body.items[0]).toMatchObject({ compressed: false, skipReason: "no-gain", mime: "image/png" });
@@ -267,6 +274,8 @@ describe("compression parameters", () => {
[ "a quality below the minimum", { quality: 5 } ],
[ "a quality above the maximum", { quality: 101 } ],
[ "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" } ]
])("400s on %s", async (_label, body) => {
const noteId = await createImageNote(smallPng);
@@ -280,17 +289,58 @@ describe("compression parameters", () => {
const noteId = await createImageNote(smallPng);
expect((await api.post(`/api/notes/${noteId}/compress-images`, { body: [ 1, 2 ] })).status).toBe(400);
- expect((await api.post(`/api/notes/${noteId}/compress-images`, { body: "convertLossless" })).status).toBe(400);
+ expect((await api.post(`/api/notes/${noteId}/compress-images`, { body: "reencode" })).status).toBe(400);
});
- it("treats a missing body as a request for the defaults", async () => {
+ it("treats a missing body as a request for both steps", async () => {
const noteId = await createImageNote(noisyPng);
const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`);
expect(res.status).toBe(200);
- // Defaults: no conversion, so a PNG within the bound is left exactly as it was.
- expect(res.body.items[0]).toMatchObject({ compressed: false, mime: "image/png" });
+ // A request that named nothing asked for the images to be compressed; answering it with a
+ // no-op because a PNG happened to fit the bound would be the surprising reading.
+ expect(res.body.items[0]).toMatchObject({ compressed: true, mime: "image/jpeg" });
+ });
+
+ it("changes nothing at all when every step is switched off", async () => {
+ 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 }
+ });
+
+ // Oversized by a long way, and still untouched: with nothing switched on, the bound is
+ // never measured against.
+ expect(res.body.items[0]).toMatchObject({ compressed: false, skipReason: "no-gain" });
+ expect(readNote(noteId).size).toBe(noisyPng.byteLength);
+ });
+
+ it.each([
+ [ "the lossy one", { reencode: true, convertLossless: false }, "jpeg.jpg" ],
+ [ "the lossless one", { reencode: false, convertLossless: true }, "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);
+ await addAttachment(noteId, "jpeg.jpg", noisyJpeg, { mime: "image/jpeg" });
+
+ const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, { body });
+
+ // Squeezing the JPEGs harder is no reason to stop a PNG being a PNG, and vice versa: each
+ // switch answers for its own kind and leaves the other exactly as it was.
+ expect(res.body.items.filter((item) => item.compressed).map((item) => item.title)).toEqual([ expected ]);
+ });
+
+ it("re-encodes without scaling when only scaling is switched off", async () => {
+ const noteId = await createImageNote(noisyPng);
+
+ const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {
+ body: { resize: false, maxWidthHeight: 100 }
+ });
+
+ expect(res.body.items[0]).toMatchObject({ compressed: true, mime: "image/jpeg" });
+ // The bound is quoted and ignored: nothing was asked to be measured against it.
+ expect(await decodedSize(noteId)).toEqual([ 600, 400 ]);
});
});
diff --git a/apps/server/src/services/image_provider.spec.ts b/apps/server/src/services/image_provider.spec.ts
index a5414cde06..16ab44d951 100644
--- a/apps/server/src/services/image_provider.spec.ts
+++ b/apps/server/src/services/image_provider.spec.ts
@@ -238,7 +238,9 @@ describe('serverImageProvider.processImage', () => {
describe('serverImageProvider.compressImage', () => {
/** Every parameter is explicit, so nothing here depends on the stored options. */
function request(overrides: Partial<ImageCompressionRequest> = {}): ImageCompressionRequest {
- return { maxWidthHeight: 2000, quality: 75, convertLossless: false, ...overrides };
+ return {
+ resize: true, maxWidthHeight: 2000, reencode: true, convertLossless: true, quality: 75, ...overrides
+ };
}
it.each([
@@ -260,27 +262,47 @@ describe('serverImageProvider.compressImage', () => {
expect(outcome.compressed).toBe(true);
});
- describe('lossless sources', () => {
- it('re-encodes an opaque PNG as JPEG once conversion is allowed', async () => {
- const outcome = await serverImageProvider.compressImage(noisyPng, request({ convertLossless: true }));
+ describe('the re-encoding switches, each answering for its own kind', () => {
+ it('converts an opaque PNG without needing anything to scale', async () => {
+ const outcome = await serverImageProvider.compressImage(noisyPng, request());
expect(outcome).toMatchObject({ compressed: true, format: { ext: 'jpg', mime: 'image/jpeg' } });
if (!outcome.compressed) return;
expect(outcome.buffer.byteLength).toBeLessThan(noisyPng.byteLength);
- // Still 600x400: converting is worthwhile on its own, without any resizing.
+ // Still 600x400: converting is the step that reaches an image already within bounds.
const decoded = await Jimp.read(Buffer.from(outcome.buffer));
expect([decoded.bitmap.width, decoded.bitmap.height]).toEqual([600, 400]);
});
- it('never re-encodes a PNG that is already within bounds when conversion is off', async () => {
- const outcome = await serverImageProvider.compressImage(noisyPng, request());
+ it('recompresses a JPEG on the lossy switch alone, converting switched off', async () => {
+ const outcome = await serverImageProvider.compressImage(
+ noisyJpeg, request({ convertLossless: false, quality: 40 }));
+
+ expect(outcome).toMatchObject({ compressed: true, format: { ext: 'jpg', mime: 'image/jpeg' } });
+ });
+
+ 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.
+ const outcome = await serverImageProvider.compressImage(
+ noisyPng, request({ convertLossless: false }));
expect(outcome).toEqual({ compressed: false, reason: 'no-gain' });
});
- it('scales an oversized PNG down but keeps it a PNG when conversion is off', async () => {
- const outcome = await serverImageProvider.compressImage(noisyPng, request({ maxWidthHeight: 100 }));
+ it('leaves a JPEG alone on the converting switch, which is not about lossy images', async () => {
+ const outcome = await serverImageProvider.compressImage(
+ noisyJpeg, request({ reencode: false }));
+
+ expect(outcome).toEqual({ compressed: false, reason: 'no-gain' });
+ });
+
+ it('scales an oversized PNG down but keeps it a PNG once converting is off', async () => {
+ const outcome = await serverImageProvider.compressImage(
+ noisyPng,
+ request({ maxWidthHeight: 100, convertLossless: false })
+ );
expect(outcome).toMatchObject({ compressed: true, format: { ext: 'png', mime: 'image/png' } });
if (!outcome.compressed) return;
@@ -288,11 +310,48 @@ describe('serverImageProvider.compressImage', () => {
const decoded = await Jimp.read(Buffer.from(outcome.buffer));
expect([decoded.bitmap.width, decoded.bitmap.height]).toEqual([100, 67]);
});
+
+ it('re-encodes an oversized image at its own size once scaling is off', async () => {
+ const outcome = await serverImageProvider.compressImage(
+ noisyPng,
+ request({ resize: false, maxWidthHeight: 100 })
+ );
+
+ expect(outcome).toMatchObject({ compressed: true, format: { ext: 'jpg', mime: 'image/jpeg' } });
+ if (!outcome.compressed) return;
+
+ // The bound is quoted and never measured against: nothing asked for it to be.
+ const decoded = await Jimp.read(Buffer.from(outcome.buffer));
+ expect([decoded.bitmap.width, decoded.bitmap.height]).toEqual([600, 400]);
+ });
+
+ it('writes a scaled JPEG at the requested quality with every re-encoding switch off', async () => {
+ // Scaling has to write a JPEG back whatever the switches say, so the quality governs
+ // this too — which is why it qualifies neither switch on its own.
+ const off = { reencode: false, convertLossless: false, maxWidthHeight: 300 };
+ const coarse = await serverImageProvider.compressImage(noisyJpeg, request({ ...off, quality: 20 }));
+ const fine = await serverImageProvider.compressImage(noisyJpeg, request({ ...off, quality: 80 }));
+
+ if (!coarse.compressed || !fine.compressed) throw new Error('expected both to compress');
+ expect(coarse.buffer.byteLength).toBeLessThan(fine.buffer.byteLength);
+ });
+
+ it.each([
+ [ 'a PNG', () => noisyPng ],
+ [ 'a JPEG', () => noisyJpeg ]
+ ])('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 })
+ );
+
+ expect(outcome).toEqual({ compressed: false, reason: 'no-gain' });
+ });
});
describe('transparency', () => {
it('refuses to convert a transparent PNG, which JPEG cannot represent', async () => {
- const outcome = await serverImageProvider.compressImage(transparentPng, request({ convertLossless: true }));
+ const outcome = await serverImageProvider.compressImage(transparentPng, request());
expect(outcome).toEqual({ compressed: false, reason: 'transparent' });
});
@@ -300,7 +359,7 @@ describe('serverImageProvider.compressImage', () => {
it('still scales a transparent PNG down, keeping both the format and the alpha channel', async () => {
const outcome = await serverImageProvider.compressImage(
transparentPng,
- request({ maxWidthHeight: 100, convertLossless: true })
+ request({ maxWidthHeight: 100 })
);
expect(outcome).toMatchObject({ compressed: true, format: { ext: 'png', mime: 'image/png' } });
@@ -319,7 +378,7 @@ describe('serverImageProvider.compressImage', () => {
await makeImage(600, 400, { noisy: true, alpha: 0xff }).getBuffer('image/png')
);
- const outcome = await serverImageProvider.compressImage(opaqueWithAlpha, request({ convertLossless: true }));
+ const outcome = await serverImageProvider.compressImage(opaqueWithAlpha, request());
expect(outcome).toMatchObject({ compressed: true, format: { ext: 'jpg', mime: 'image/jpeg' } });
});
@@ -361,7 +420,7 @@ describe('serverImageProvider.compressImage', () => {
it('scales a tall image by its height', async () => {
const outcome = await serverImageProvider.compressImage(
tallPng,
- request({ maxWidthHeight: 120, convertLossless: true })
+ request({ maxWidthHeight: 120 })
);
if (!outcome.compressed) throw new Error('expected compression');
diff --git a/apps/server/src/services/image_provider.ts b/apps/server/src/services/image_provider.ts
index 0705dab984..2b19eb62dc 100644
--- a/apps/server/src/services/image_provider.ts
+++ b/apps/server/src/services/image_provider.ts
@@ -143,17 +143,29 @@ export const serverImageProvider: ImageProvider = {
const start = Date.now();
const image = await Jimp.read(Buffer.from(buffer));
const { width, height } = image.bitmap;
- const needsResize = Math.max(width, height) > request.maxWidthHeight;
+ const needsResize = request.resize && Math.max(width, height) > request.maxWidthHeight;
const isLossless = format.ext === "png";
- // JPEG has no alpha channel, so a transparent PNG would come back with its transparency
- // filled in — the one conversion that visibly damages an image rather than degrading it.
- // The check reads the decoded pixels, so it is exact rather than a guess from the header.
+ // What the image will be written back as. A JPEG can only be written back as one; a PNG
+ // becomes one only if converting was asked for and there is no transparency to lose — JPEG
+ // has no alpha channel, so converting is the one step that visibly damages an image rather
+ // than degrading it. The check reads the decoded pixels, so it is exact rather than a guess
+ // from the header.
const toJpeg = !isLossless || (request.convertLossless && !hasTransparency(image));
- if (!toJpeg && !needsResize) {
- // Nothing left to do: re-encoding a PNG at its own size is lossless and pointless.
- return { compressed: false, reason: isLossless && request.convertLossless ? "transparent" : "no-gain" };
+ // 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;
+
+ 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.
+ reason: isLossless && request.convertLossless ? "transparent" : "no-gain"
+ };
}
if (needsResize) {
@@ -167,7 +179,8 @@ export const serverImageProvider: ImageProvider = {
let result: Uint8Array;
if (toJpeg) {
- // Whatever transparency survives here is known to be absent or deliberately discarded.
+ // Reached either by conversion, which has already established there is no transparency
+ // 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 {
diff --git a/apps/standalone/src/services/image_provider.spec.ts b/apps/standalone/src/services/image_provider.spec.ts
index 2b86441299..16227aa21c 100644
--- a/apps/standalone/src/services/image_provider.spec.ts
+++ b/apps/standalone/src/services/image_provider.spec.ts
@@ -84,7 +84,9 @@ describe("standaloneImageProvider.compressImage", () => {
const buffer = withMagic([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
await expect(
- standaloneImageProvider.compressImage(buffer, { maxWidthHeight: 100, quality: 75, convertLossless: true })
+ standaloneImageProvider.compressImage(buffer, {
+ resize: true, maxWidthHeight: 100, reencode: true, convertLossless: 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.ts
index d40a81754e..7ea63ec04a 100644
--- a/packages/commons/src/lib/server_api.ts
+++ b/packages/commons/src/lib/server_api.ts
@@ -293,20 +293,42 @@ export interface SubtreeSizeResponse {
*/
export interface ImageCompressionOptions {
/**
- * Longest edge, in pixels: an image larger than this is scaled down to fit, one smaller is left
- * at its size. Omitted, it falls back to the `imageMaxWidthHeight` option.
+ * Whether an image larger than {@link maxWidthHeight} is scaled down to fit. On its own this
+ * reaches only oversized images; one already within the bound is left exactly as it is.
+ *
+ * Defaults to on, as does {@link reencode}: the endpoint is only ever invoked deliberately, and
+ * a request that asked for compression and got a no-op would be the surprising answer.
*/
+ resize?: boolean;
+ /** Longest edge in pixels. Omitted, it falls back to the `imageMaxWidthHeight` option. */
maxWidthHeight?: number;
/**
- * JPEG quality, 10 to 100. Omitted, it falls back to the `imageJpegQuality` option (75 by
- * default). Only reaches images actually encoded as JPEG — see {@link convertLossless}.
+ * Whether an image that is *already* lossy — a JPEG — is recompressed at {@link quality} even
+ * when nothing needs scaling. It costs quality every time it runs, on an image that has already
+ * paid that cost once.
+ *
+ * Says nothing about lossless sources, which is {@link convertLossless}'s to answer: the two
+ * are separate choices, and squeezing the JPEGs harder is no reason to stop a PNG being a PNG.
*/
- quality?: number;
+ reencode?: boolean;
/**
- * Whether a lossless source (PNG) may be re-encoded as JPEG. Off by default, since that trades
- * away quality permanently; with it off a PNG is only ever scaled down, never re-encoded.
+ * Whether a lossless source — a PNG — may be re-encoded as JPEG at {@link quality}. This is
+ * where most of the saving comes from, and it is also the one step that changes what kind of
+ * 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.
*/
convertLossless?: boolean;
+ /**
+ * JPEG quality, 10 to 100. Omitted, it falls back to the `imageJpegQuality` option (75 by
+ * default).
+ *
+ * Applies whenever the output is a JPEG, which is not only when {@link reencode} is on: scaling
+ * a JPEG has to write one back, so the quality governs that too.
+ */
+ quality?: number;
/**
* Whether the run visits the note's whole subtree rather than the note alone. Off by default,
* and opt-in for a reason: a descendant may be a clone, so compressing it degrades an image
@@ -330,13 +352,16 @@ 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 no resizing to do besides. */
+ /** A PNG carrying transparency, which JPEG cannot represent, and nothing to scale besides. */
| "transparent"
/** The rendered picture of a canvas/mermaid/mind map/spreadsheet note, regenerated on save. */
| "generated"
/** Protected, with no protected session open to decrypt it. */
| "protected"
- /** Compressing produced nothing smaller, so the original was kept. */
+ /**
+ * Nothing was asked of this image that would change it — an image within the bound with
+ * re-encoding off, or both switched off — or compressing it produced nothing smaller.
+ */
| "no-gain"
/** This build has no image compression at all (the standalone/WASM runtime). */
| "unsupported-platform"
diff --git a/packages/trilium-core/src/services/image_compression.ts b/packages/trilium-core/src/services/image_compression.ts
index dc532f74c0..7c89510bad 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 { maxWidthHeight, quality, convertLossless } = options;
+ const { resize, maxWidthHeight, reencode, convertLossless, 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.`);
@@ -72,26 +72,34 @@ export function resolveCompressionRequest(options: ImageCompressionOptions = {})
throw new ValidationError(`quality must be an integer between ${MIN_QUALITY} and ${MAX_QUALITY}.`);
}
- if (convertLossless !== undefined && typeof convertLossless !== "boolean") {
- throw new ValidationError("convertLossless must be a boolean.");
- }
+ requireBoolean(resize, "resize");
+ requireBoolean(reencode, "reencode");
+ requireBoolean(convertLossless, "convertLossless");
return {
+ // All three default 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"),
- quality: quality ?? defaultQuality(),
- convertLossless: convertLossless ?? false
+ reencode: reencode ?? true,
+ convertLossless: convertLossless ?? true,
+ quality: quality ?? defaultQuality()
};
}
+function requireBoolean(value: unknown, name: string) {
+ if (value !== undefined && typeof value !== "boolean") {
+ throw new ValidationError(`${name} must be a boolean.`);
+ }
+}
+
/**
* Whether the run descends into the note's subtree. Read apart from {@link resolveCompressionRequest}
* because it says nothing about how an image is compressed, only about which images are visited —
* so the provider never sees it. The attachment endpoint has no use for it and does not read it.
*/
export function resolveRecursive(options: ImageCompressionOptions = {}): boolean {
- if (options.recursive !== undefined && typeof options.recursive !== "boolean") {
- throw new ValidationError("recursive must be a boolean.");
- }
+ requireBoolean(options.recursive, "recursive");
return options.recursive === true;
}
diff --git a/packages/trilium-core/src/services/image_provider.ts b/packages/trilium-core/src/services/image_provider.ts
index c886b304d0..d1b3748394 100644
--- a/packages/trilium-core/src/services/image_provider.ts
+++ b/packages/trilium-core/src/services/image_provider.ts
@@ -21,12 +21,16 @@ export interface ProcessedImage {
* never has to reach for an option itself.
*/
export interface ImageCompressionRequest {
- /** Longest edge in pixels; a larger image is scaled down to fit. */
+ /** Whether an image larger than {@link maxWidthHeight} is scaled down to fit. */
+ resize: boolean;
+ /** Longest edge in pixels. Only consulted when {@link resize} is on. */
maxWidthHeight: number;
- /** JPEG quality, 10 to 100. */
- quality: number;
- /** Whether a lossless source (PNG) may be re-encoded as JPEG. */
+ /** Whether an already-lossy image (JPEG) is recompressed even when nothing needs scaling. */
+ reencode: boolean;
+ /** Whether a lossless image (PNG) may be re-encoded as JPEG. */
convertLossless: boolean;
+ /** JPEG quality, 10 to 100, applied whenever the output is a JPEG. */
+ quality: number;
}
export type ImageCompressionOutcome =