Skip to content

Build your personal knowledge base with Trilium Notes

client/image compression tool: redo the PNG options

Adorian Doran75b05ff9dd3b
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 6fb9baf7ca..271dcb49b7 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2922,10 +2922,12 @@
"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 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_png_handling": "PNG images",
+ "compress_png_handling_help": "Only one of these can happen to a given PNG. Keeping it leaves every pixel intact, so only resizing can shrink it. Optimizing reduces it to a palette of 256 colors and writes it back as a PNG: lossy and permanent, though images with few colors, such as screenshots and diagrams, usually look unchanged, and transparency is preserved. Converting to JPEG usually saves the most, but the image stops being a PNG; images with transparency cannot be converted, as JPEG cannot store it, and are optimized instead.",
+ "compress_png_keep": "Keep as they are",
+ "compress_png_optimize": "Optimize",
+ "compress_png_jpeg": "Convert to JPEG",
+ "compress_quality": "Quality",
"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 4fa119ef39..e26a283e38 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
@@ -193,23 +193,22 @@ describe("showImageCompressionDialog", () => {
// 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",
- // 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.
+ // Straight after the step it governs rather than nested under it: scaling writes a
+ // JPEG back too, so it is in force for either.
"images.jpeg_quality",
+ // One exclusive choice, since only one of the three can happen to a given PNG.
+ "space_usage.compress_png_handling",
"space_usage.compress_process_child_notes"
]);
expect(rows().map(controlOf))
- .toEqual([ "toggle", "number", "toggle", "toggle", "toggle", "slider", "toggle" ]);
- expect(rows().map(isNested)).toEqual([ false, true, false, false, false, false, false ]);
+ .toEqual([ "toggle", "number", "toggle", "slider", "choice", "toggle" ]);
+ expect(rows().map(isNested)).toEqual([ false, true, 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, true, false, true ]);
+ .toEqual([ true, false, true, false, true, true ]);
});
it("shows the bound only while there is a step that measures against it", async () => {
@@ -229,13 +228,27 @@ describe("showImageCompressionDialog", () => {
await toggle(toggles()[0]);
await toggle(toggles()[1]);
- await toggle(toggles()[2]);
- await toggle(toggles()[3]);
+ await chooseHandling("keep");
expect(titles()).toContain("images.jpeg_quality");
expect(slider()).not.toBeNull();
});
+ it("shows the conversion quality only while converting is the chosen handling", async () => {
+ await openDialog();
+
+ // Nested under the choice it qualifies, and under nothing else: it is the one setting that
+ // governs that handling alone.
+ expect(titles()).not.toContain("space_usage.compress_quality");
+
+ await chooseHandling("jpeg");
+ expect(titles()).toContain("space_usage.compress_quality");
+ expect(rows().map(isNested)).toEqual([ false, true, false, false, false, true, false ]);
+
+ await chooseHandling("optimize");
+ expect(titles()).not.toContain("space_usage.compress_quality");
+ });
+
it("drops the subtree row for an attachment, which has no subtree to reach into", async () => {
await openDialog(ATTACHMENT_TARGET);
@@ -243,9 +256,8 @@ describe("showImageCompressionDialog", () => {
"space_usage.compress_reduce_resolution",
"images.max_image_dimensions",
"space_usage.compress_reencode",
- "space_usage.compress_convert_lossless",
- "space_usage.compress_optimize_png",
- "images.jpeg_quality"
+ "images.jpeg_quality",
+ "space_usage.compress_png_handling"
]);
});
@@ -254,7 +266,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()[5].children).map((child) => child.classList[0])).toEqual([
+ expect(Array.from(rows()[3].children).map((child) => child.classList[0])).toEqual([
"image-compression-section-title",
"image-compression-section-value",
"slider"
@@ -277,15 +289,27 @@ describe("showImageCompressionDialog", () => {
// 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, true, false ]);
+ expect(toggles().map((input) => input.checked)).toEqual([ true, true, false ]);
+ // PNGs start on being made smaller without ceasing to be PNGs, which is the least
+ // surprising thing to do by default.
+ expect(chosenHandling()).toBe("space_usage.compress_png_optimize");
});
it("keeps a stored answer of off for a step, rather than reasserting the default", async () => {
- mocks.storedOption = JSON.stringify({ convertLossless: false });
+ mocks.storedOption = JSON.stringify({ reencode: false, pngHandling: "keep" });
+
+ await openDialog();
+
+ expect(toggles().map((input) => input.checked)).toEqual([ true, false, false ]);
+ expect(chosenHandling()).toBe("space_usage.compress_png_keep");
+ });
+
+ it("falls back to optimizing on a stored handling it does not recognise", async () => {
+ mocks.storedOption = JSON.stringify({ pngHandling: "shrink" });
await openDialog();
- expect(toggles().map((input) => input.checked)).toEqual([ true, true, false, true, false ]);
+ expect(chosenHandling()).toBe("space_usage.compress_png_optimize");
});
it("reads a stored answer back, and lets it override the image options", async () => {
@@ -297,7 +321,7 @@ describe("showImageCompressionDialog", () => {
expect(numberField()?.value).toBe("800");
expect(slider()?.value).toBe("35");
- expect(toggles().map((input) => input.checked)).toEqual([ true, false, true, true, true ]);
+ expect(toggles().map((input) => input.checked)).toEqual([ true, false, true ]);
});
it.each([
@@ -326,16 +350,17 @@ describe("showImageCompressionDialog", () => {
await type(numberField(), "900");
await drag(slider(), "45");
await toggle(toggles()[1]);
- await toggle(toggles()[4]);
+ await chooseHandling("jpeg");
+ await toggle(toggles()[2]);
// 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,
- optimizePNG: true,
+ pngHandling: "jpeg",
quality: 45,
+ conversionQuality: 85,
processChildNotes: true
}));
});
@@ -345,15 +370,14 @@ describe("showImageCompressionDialog", () => {
await toggle(toggles()[0]);
await toggle(toggles()[1]);
- await toggle(toggles()[2]);
- await toggle(toggles()[3]);
+ await chooseHandling("keep");
// 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]);
+ await chooseHandling("optimize");
expect(compressButton()?.disabled).toBe(false);
});
@@ -368,7 +392,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()[4]);
+ await toggle(toggles()[2]);
await click(cancelButton());
// The answer is "no run", and nothing was asked of the server — but the settings are kept
@@ -384,7 +408,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()[4]);
+ await toggle(toggles()[2]);
await click(compressButton());
await closed;
@@ -393,9 +417,9 @@ describe("running the compression", () => {
resize: true,
maxWidthHeight: CONFIGURED_MAX_DIMENSIONS,
reencode: true,
- convertLossless: true,
- optimizePNG: true,
+ pngHandling: "optimize",
quality: CONFIGURED_QUALITY,
+ conversionQuality: 85,
recursive: true
});
});
@@ -408,7 +432,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, optimizePNG: true });
+ expect(postedBody()).toMatchObject({ resize: false, reencode: true, pngHandling: "optimize" });
});
it("sends nothing about subtrees to the attachment endpoint, which has no use for it", async () => {
@@ -487,6 +511,21 @@ describe("running the compression", () => {
});
});
+/** The segmented choice buttons, in the order they are offered. */
+const choiceButtons = () =>
+ Array.from(document.body.querySelectorAll<HTMLButtonElement>(".image-compression-section-choice button"));
+
+/** The label of the choice currently highlighted. */
+function chosenHandling() {
+ return choiceButtons().find((button) => button.classList.contains("active"))?.textContent?.trim();
+}
+
+/** Picks a handling by its position, the way a click on that button does. */
+async function chooseHandling(handling: "keep" | "optimize" | "jpeg") {
+ const index = [ "keep", "optimize", "jpeg" ].indexOf(handling);
+ await click(choiceButtons()[index]);
+}
+
/** 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");
@@ -500,6 +539,9 @@ function controlOf(row: HTMLElement) {
if (row.querySelector(".slider")) {
return "slider";
}
+ if (row.querySelector(".image-compression-section-choice")) {
+ return "choice";
+ }
return row.querySelector(".switch-toggle") ? "toggle" : "none";
}
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 4f39d3c734..5b54a46e92 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
@@ -22,9 +22,8 @@ import {
readImageCompressionOptions
} from "./image_compression_options";
import {
- ConvertLosslessSection,
JpegQualitySection,
- OptimizePngSection,
+ PngHandlingSection,
ProcessChildNotesSection,
ReduceResolutionSection,
ReencodeImagesSection
@@ -135,11 +134,11 @@ function ImageCompressionDialog({ target, onFinished }: {
<Card className="image-compression-settings">
<ReduceResolutionSection {...sectionProps} />
<ReencodeImagesSection {...sectionProps} />
- <ConvertLosslessSection {...sectionProps} />
- <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. */}
+ {/* Straight after the step it governs, rather than under it: scaling a JPEG has to
+ write one back too, so it is in force for either. */}
<JpegQualitySection {...sectionProps} />
+ {/* Last of the three, since converting brings a quality of its own nested beneath. */}
+ <PngHandlingSection {...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 23fecba187..326a7f338f 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
@@ -36,9 +36,9 @@ export function runImageCompression(
resize: options.resize,
maxWidthHeight: options.maxWidthHeight,
reencode: options.reencode,
- convertLossless: options.convertLossless,
- optimizePNG: options.optimizePNG,
+ pngHandling: options.pngHandling,
quality: options.quality,
+ conversionQuality: options.conversionQuality,
// 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 8bf196ef4b..d0f0400a3d 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
@@ -1,10 +1,12 @@
+import { IMAGE_PNG_HANDLINGS, type ImagePngHandling } from "@triliumnext/commons";
+
import optionService from "../../../../../services/options";
/**
* What the image compression tool is set to do. Persisted as JSON in the `imageCompressionToolOptions`
* option, so the next run opens on the last answer rather than on a fresh set of defaults.
*
- * The first three mirror the server's `ImageCompressionOptions`; {@link processChildNotes} is the
+ * All but the last mirror the server's `ImageCompressionOptions`; {@link processChildNotes} is the
* tool's own, the endpoint acting on one note at a time.
*/
export interface ImageCompressionToolOptions {
@@ -14,22 +16,22 @@ export interface ImageCompressionToolOptions {
maxWidthHeight: number;
/** 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;
- /** 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. */
+ /** What becomes of a lossless image (PNG): left alone, quantized in place, or converted. */
+ pngHandling: ImagePngHandling;
+ /** JPEG quality, {@link MIN_QUALITY} to {@link MAX_QUALITY}, for an already-lossy image. */
quality: number;
+ /** JPEG quality, {@link MIN_QUALITY} to {@link MAX_QUALITY}, for converting a lossless one. */
+ conversionQuality: 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.
+ * Whether the settings amount to anything at all. With nothing asked of either kind of image, every
+ * one of them 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 || options.optimizePNG;
+ return options.resize || options.reencode || options.pngHandling !== "keep";
}
/** The bounds the server validates against; the controls here never offer a value it would reject. */
@@ -42,15 +44,14 @@ export const MIN_MAX_WIDTH_HEIGHT = 1;
/**
* Fills a stored setting out into the full set the dialog works with.
*
- * The two numbers fall back to the image options rather than to constants of their own, so a tool
- * 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.
+ * The dimension bound and the recompression quality fall back to the image options rather than to
+ * constants of their own, so a tool 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.
*
- * 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.
+ * PNGs start on optimizing, matching the server: it makes an image smaller without changing what it
+ * is, which is the least surprising thing to do by default. 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
@@ -61,9 +62,11 @@ export function readImageCompressionOptions(
? Number(stored?.maxWidthHeight)
: defaultMaxWidthHeight(),
reencode: stored?.reencode ?? true,
- convertLossless: stored?.convertLossless ?? true,
- optimizePNG: stored?.optimizePNG ?? true,
+ pngHandling: readPngHandling(stored?.pngHandling),
quality: isQuality(stored?.quality) ? Number(stored?.quality) : defaultQuality(),
+ conversionQuality: isQuality(stored?.conversionQuality)
+ ? Number(stored?.conversionQuality)
+ : DEFAULT_CONVERSION_QUALITY,
processChildNotes: stored?.processChildNotes === true
};
}
@@ -88,6 +91,18 @@ export function defaultQuality(): number {
*/
const FALLBACK_MAX_WIDTH_HEIGHT = 2000;
+/**
+ * Where converting starts, above {@link DEFAULT_QUALITY} and matching the server's own default:
+ * converting a lossless original gives up detail that was genuinely there, where recompressing an
+ * already-lossy image works on detail that is long gone.
+ */
+export const DEFAULT_CONVERSION_QUALITY = 85;
+
+/** Anything unrecognised falls back to optimizing, the choice that changes an image least. */
+function readPngHandling(value: unknown): ImagePngHandling {
+ return IMAGE_PNG_HANDLINGS.includes(value as ImagePngHandling) ? value as ImagePngHandling : "optimize";
+}
+
function isPositiveInteger(value: unknown): boolean {
return Number.isInteger(value) && Number(value) >= MIN_MAX_WIDTH_HEIGHT;
}
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 1676c26cc3..d30c13d87a 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
@@ -42,6 +42,13 @@
.switch-widget {
flex: 0 0 auto;
}
+
+ /* Never wraps: the choices are read across, and a button folding onto a second line would
+ break the row into two heights. A long translation widens the dialog instead. */
+ .image-compression-section-choice {
+ flex: 0 0 auto;
+ white-space: nowrap;
+ }
}
/* Indented by the card itself; quieting the title is what marks it as qualifying the row above
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 b65154c12e..dd4c644912 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
@@ -1,10 +1,14 @@
import "./image_compression_sections.css";
+import { IMAGE_PNG_HANDLINGS } from "@triliumnext/commons";
+import clsx from "clsx";
+
import { t } from "../../../../../services/i18n";
import { CardSection } from "../../../../react/Card";
import ContextualHelp from "../../../../react/ContextualHelp";
import { FormTextBoxWithUnit } from "../../../../react/FormTextBox";
import FormToggle from "../../../../react/FormToggle";
+import SegmentedChoice from "../../../../react/SegmentedChoice";
import Slider from "../../../../react/Slider";
import {
type ImageCompressionToolOptions,
@@ -101,45 +105,50 @@ export function ReencodeImagesSection({ options, onChange, disabled }: ImageComp
}
/**
- * 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.
+ * What becomes of a PNG — one exclusive choice rather than a set of switches, because only one of
+ * the three can ever happen to a given image: it survives as it is, survives smaller, or stops
+ * being a PNG. Two toggles would claim they combine, and they do not.
+ *
+ * Converting brings its own quality with it, nested underneath: it is the only setting that
+ * qualifies this choice alone, and someone converting a pristine original may well want more
+ * quality here than they would spend recompressing an image that is already lossy.
*/
-export function ConvertLosslessSection({ options, onChange, disabled }: ImageCompressionSectionProps) {
+export function PngHandlingSection(props: ImageCompressionSectionProps) {
+ const { options, onChange, disabled } = props;
+
return (
- <CardSection className="image-compression-section">
+ <CardSection
+ className="image-compression-section"
+ subSectionsVisible={options.pngHandling === "jpeg"}
+ subSections={[ <ConversionQualitySection key="conversion-quality" {...props} /> ]}
+ >
<span className="image-compression-section-title">
- {t("space_usage.compress_convert_lossless")}
- <ContextualHelp helpMessage={t("space_usage.compress_convert_lossless_help")} />
+ {t("space_usage.compress_png_handling")}
+ <ContextualHelp helpMessage={t("space_usage.compress_png_handling_help")} />
</span>
- <FormToggle
- disabled={disabled}
- currentValue={options.convertLossless}
- onChange={(value) => onChange({ convertLossless: value })}
+ <SegmentedChoice
+ className="image-compression-section-choice"
+ currentValue={disabled ? "" : options.pngHandling}
+ options={IMAGE_PNG_HANDLINGS.map((value) => ({
+ value,
+ label: t(`space_usage.compress_png_${value}`)
+ }))}
+ onChange={(value) => !disabled && onChange({ pngHandling: value })}
/>
</CardSection>
);
}
-/**
- * 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) {
+/** The quality a converted PNG is written at, kept apart from the recompression quality above. */
+export function ConversionQualitySection({ 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>
+ <QualitySlider
+ label={t("space_usage.compress_quality")}
+ value={options.conversionQuality}
+ disabled={disabled}
+ onChange={(value) => onChange({ conversionQuality: value })}
+ nested
+ />
);
}
@@ -153,18 +162,12 @@ export function OptimizePngSection({ options, onChange, disabled }: ImageCompres
*/
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>
+ <QualitySlider
+ label={t("images.jpeg_quality")}
+ value={options.quality}
+ disabled={disabled}
+ onChange={(value) => onChange({ quality: value })}
+ />
);
}
@@ -184,3 +187,34 @@ export function ProcessChildNotesSection({ options, onChange, disabled }: ImageC
</CardSection>
);
}
+
+/**
+ * The row shared by both qualities: a title, the current figure, and the slider it reads.
+ *
+ * The figure sits between the two 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.
+ */
+function QualitySlider({ label, value, onChange, disabled, nested }: {
+ label: string;
+ value: number;
+ onChange: (value: number) => void;
+ disabled?: boolean;
+ nested?: boolean;
+}) {
+ return (
+ <CardSection className={clsx("image-compression-section", nested && "image-compression-section-nested")}>
+ <span className="image-compression-section-title">{label}</span>
+ <span className="image-compression-section-value">
+ {t("space_usage.compress_quality_value", { quality: value })}
+ </span>
+ <Slider
+ min={MIN_QUALITY}
+ max={MAX_QUALITY}
+ step={QUALITY_STEP}
+ disabled={disabled}
+ value={value}
+ onChange={onChange}
+ />
+ </CardSection>
+ );
+}
diff --git a/apps/server/src/services/image_compression.spec.ts b/apps/server/src/services/image_compression.spec.ts
index 4b0f020e2a..12f2ba39dc 100644
--- a/apps/server/src/services/image_compression.spec.ts
+++ b/apps/server/src/services/image_compression.spec.ts
@@ -16,7 +16,12 @@ import { afterEach, beforeAll, describe, expect, it } from "vitest";
*/
let api: CoreApiTester;
-/** A large noisy PNG: big enough that both converting and resizing it save real bytes. */
+/**
+ * A large photograph-shaped PNG: smooth, spatially correlated colour over thousands of distinct
+ * values, which is what makes every step worth doing to it — PNG stores it poorly, JPEG stores it
+ * well, and a palette of 256 is a real reduction. Uncorrelated noise would be the opposite on all
+ * three counts and could not show any of them working.
+ */
let noisyPng: Uint8Array;
/** An 8x8 solid PNG, which nothing can make smaller. */
let smallPng: Uint8Array;
@@ -31,22 +36,12 @@ beforeAll(async () => {
api = CoreApiTester.build();
const noisy = new Jimp({ width: 600, height: 400, color: 0x3366ccff });
- 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) | 0xff) >>> 0;
- noisy.setPixelColor(color, x, y);
- }
- }
+ paintPhoto(noisy, 0xff);
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);
- }
- }
+ paintPhoto(translucent, 0x80);
transparentPng = new Uint8Array(await translucent.getBuffer("image/png"));
const small = new Jimp({ width: 8, height: 8, color: 0x3366ccff });
@@ -73,7 +68,7 @@ describe("compress note images (POST /api/notes/:noteId/compress-images)", () =>
const noteId = await createImageNote(noisyPng);
const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {
- body: { convertLossless: true }
+ body: { pngHandling: "jpeg" }
});
expect(res.status).toBe(200);
@@ -100,7 +95,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, optimizePNG: false }
+ body: { pngHandling: "keep" }
});
expect(res.body.compressedCount).toBe(0);
@@ -120,7 +115,7 @@ describe("compress note images (POST /api/notes/:noteId/compress-images)", () =>
await addAttachment(noteId, "notes.txt", new Uint8Array([ 1, 2, 3 ]), { role: "file", mime: "text/plain" });
const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {
- body: { convertLossless: true }
+ body: { pngHandling: "jpeg" }
});
expect(res.body.items.map((item) => item.entityId).sort()).toEqual([ big, small ].sort());
@@ -150,7 +145,7 @@ describe("compress note images (POST /api/notes/:noteId/compress-images)", () =>
const childId = await createImageNote(noisyPng, noteId);
const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {
- body: { convertLossless: true }
+ body: { pngHandling: "jpeg" }
});
expect(res.body.items).toHaveLength(0);
@@ -167,7 +162,7 @@ describe("compress note images (POST /api/notes/:noteId/compress-images)", () =>
await api.put(`/api/notes/${grandchildId}/clone-to-note/${noteId}`);
const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {
- body: { convertLossless: true, recursive: true }
+ body: { pngHandling: "jpeg", recursive: true }
});
expect(res.body.items.map((item) => item.entityId).sort())
@@ -191,7 +186,7 @@ describe("compress note images (POST /api/notes/:noteId/compress-images)", () =>
setNoteType(noteId, "spreadsheet", "application/json");
const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {
- body: { convertLossless: true }
+ body: { pngHandling: "jpeg" }
});
expect(res.body.items[0]).toMatchObject({
@@ -209,7 +204,7 @@ describe("compress note images (POST /api/notes/:noteId/compress-images)", () =>
cls.init(() => { becca.getNoteOrThrow(noteId).isProtected = true; });
const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {
- body: { convertLossless: true }
+ body: { pngHandling: "jpeg" }
});
expect(res.body.items[0]).toMatchObject({ compressed: false, skipReason: "protected", originalSize: 0 });
@@ -221,7 +216,7 @@ describe("compress note images (POST /api/notes/:noteId/compress-images)", () =>
const noteId = await createImageNote(corruptPng);
const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {
- body: { convertLossless: true, maxWidthHeight: 100 }
+ body: { pngHandling: "jpeg", maxWidthHeight: 100 }
});
expect(res.status).toBe(200);
@@ -235,7 +230,7 @@ describe("compress note images (POST /api/notes/:noteId/compress-images)", () =>
const good = await addAttachment(noteId, "good.png", noisyPng);
const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {
- body: { convertLossless: true }
+ body: { pngHandling: "jpeg" }
});
expect(itemFor(res.body, broken).skipReason).toBe("error");
@@ -256,27 +251,41 @@ describe("compression parameters", () => {
cls.init(() => options.setOption("imageMaxWidthHeight", "150"));
const noteId = await createImageNote(noisyPng);
- await api.post(`/api/notes/${noteId}/compress-images`, { body: { convertLossless: true } });
+ await api.post(`/api/notes/${noteId}/compress-images`, { body: { pngHandling: "jpeg" } });
expect(await decodedSize(noteId)).toEqual([ 150, 100 ]);
});
- it("honours the requested quality, and falls back to the imageJpegQuality option without one", async () => {
- const explicitLow = await compressedSize({ convertLossless: true, quality: 20 });
- const explicitHigh = await compressedSize({ convertLossless: true, quality: 70 });
+ it("honours the recompression quality, falling back to the imageJpegQuality option", async () => {
+ const explicitLow = await compressedSize({ quality: 20 }, noisyJpeg);
+ const explicitHigh = await compressedSize({ quality: 70 }, noisyJpeg);
expect(explicitLow).toBeLessThan(explicitHigh);
cls.init(() => options.setOption("imageJpegQuality", "20"));
- expect(await compressedSize({ convertLossless: true })).toBe(explicitLow);
+ expect(await compressedSize({}, noisyJpeg)).toBe(explicitLow);
});
- it("falls back to the default quality when the stored option is out of range", async () => {
+ it("falls back to the default recompression quality when the stored option is out of range", async () => {
cls.init(() => options.setOption("imageJpegQuality", "75"));
- const at75 = await compressedSize({ convertLossless: true });
+ const at75 = await compressedSize({}, noisyJpeg);
// An option the caller did not choose and cannot fix from here must not fail the request.
cls.init(() => options.setOption("imageJpegQuality", "500"));
- expect(await compressedSize({ convertLossless: true })).toBe(at75);
+ expect(await compressedSize({}, noisyJpeg)).toBe(at75);
+ });
+
+ it("honours the conversion quality, which follows no option and no other quality", async () => {
+ const converting = { pngHandling: "jpeg" };
+ const low = await compressedSize({ ...converting, conversionQuality: 20 });
+ const high = await compressedSize({ ...converting, conversionQuality: 70 });
+ expect(low).toBeLessThan(high);
+
+ // The image option governs recompressing, not converting: a lossless original is a
+ // different trade, so its quality keeps a default of its own and is unmoved by either.
+ cls.init(() => options.setOption("imageJpegQuality", "20"));
+ const atDefault = await compressedSize(converting);
+ expect(await compressedSize({ ...converting, quality: 20 })).toBe(atDefault);
+ expect(atDefault).toBeGreaterThan(high);
});
it.each([
@@ -287,8 +296,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 optimizePNG", { optimizePNG: "yes" } ]
+ [ "an unknown pngHandling", { pngHandling: "shrink" } ],
+ [ "a conversion quality out of range", { conversionQuality: 5 } ]
])("400s on %s", async (_label, body) => {
const noteId = await createImageNote(smallPng);
@@ -304,15 +313,15 @@ describe("compression parameters", () => {
expect((await api.post(`/api/notes/${noteId}/compress-images`, { body: "reencode" })).status).toBe(400);
});
- it("treats a missing body as a request for both steps", async () => {
+ it("treats a missing body as a request to compress without changing formats", async () => {
const noteId = await createImageNote(noisyPng);
const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`);
expect(res.status).toBe(200);
- // 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" });
+ // A request that named nothing asked for the images to be compressed, so answering with a
+ // no-op would be the surprising reading — but it did not ask for the format to change.
+ expect(res.body.items[0]).toMatchObject({ compressed: true, mime: "image/png" });
});
it("changes nothing at all when every step is switched off", async () => {
@@ -320,8 +329,7 @@ describe("compression parameters", () => {
const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {
body: {
- resize: false, reencode: false, convertLossless: false, optimizePNG: false,
- maxWidthHeight: 10
+ resize: false, reencode: false, pngHandling: "keep", maxWidthHeight: 10
}
});
@@ -332,8 +340,8 @@ describe("compression parameters", () => {
});
it.each([
- [ "the lossy one", { reencode: true, convertLossless: false, optimizePNG: false }, "jpeg.jpg" ],
- [ "the lossless one", { reencode: false, convertLossless: true, optimizePNG: false }, "png.png" ]
+ [ "the lossy one", { reencode: true, pngHandling: "keep" }, "jpeg.jpg" ],
+ [ "the lossless one", { reencode: false, pngHandling: "jpeg" }, "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);
@@ -365,7 +373,7 @@ describe("compression parameters", () => {
const noteId = await createImageNote(noisyPng);
const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {
- body: { resize: false, maxWidthHeight: 100 }
+ body: { resize: false, maxWidthHeight: 100, pngHandling: "jpeg" }
});
expect(res.body.items[0]).toMatchObject({ compressed: true, mime: "image/jpeg" });
@@ -396,7 +404,7 @@ describe("compress one attachment (POST /api/attachments/:attachmentId/compress-
const sibling = await addAttachment(noteId, "sibling.png", noisyPng);
const res = await api.post<ImageCompressionResponse>(`/api/attachments/${target}/compress-image`, {
- body: { convertLossless: true }
+ body: { pngHandling: "jpeg" }
});
expect(res.body.items).toHaveLength(1);
@@ -411,21 +419,36 @@ describe("compress one attachment (POST /api/attachments/:attachmentId/compress-
setNoteType(noteId, "spreadsheet", "application/json");
const res = await api.post<ImageCompressionResponse>(`/api/attachments/${attachmentId}/compress-image`, {
- body: { convertLossless: true }
+ body: { pngHandling: "jpeg" }
});
expect(res.body.items[0]).toMatchObject({ compressed: false, skipReason: "generated" });
});
});
+/**
+ * Paints the fixture: smooth sine gradients across all three channels, giving a picture with the
+ * statistics of a photograph — many distinct colours, strongly correlated between neighbours.
+ */
+function paintPhoto(image: InstanceType<typeof Jimp>, alpha: number) {
+ for (let x = 0; x < 600; x++) {
+ for (let y = 0; y < 400; y++) {
+ const r = Math.round(128 + 127 * Math.sin(x / 40));
+ const g = Math.round(128 + 127 * Math.sin(y / 30));
+ const b = Math.round(128 + 127 * Math.sin((x + y) / 50));
+ image.setPixelColor((((r << 24) | (g << 16) | (b << 8) | alpha) >>> 0), x, y);
+ }
+ }
+}
+
/** Creates a real image note holding the given bytes and returns its noteId. */
-async function createImageNote(content: Uint8Array, parentNoteId = "root"): Promise<string> {
+async function createImageNote(content: Uint8Array, parentNoteId = "root", mime = "image/png"): Promise<string> {
const { noteId } = await createTextNote(api, { parentNoteId });
cls.init(() => getSql().transactional(() => {
const note = becca.getNoteOrThrow(noteId);
note.type = "image";
- note.mime = "image/png";
+ note.mime = mime;
note.save();
note.setContent(content, { forceSave: true });
}));
@@ -479,8 +502,8 @@ function itemFor(response: ImageCompressionResponse, entityId: string) {
}
/** Compresses a fresh copy of the noisy PNG and returns how many bytes it ended up at. */
-async function compressedSize(body: Record<string, unknown>): Promise<number> {
- const noteId = await createImageNote(noisyPng);
+async function compressedSize(body: Record<string, unknown>, source = noisyPng): Promise<number> {
+ const noteId = await createImageNote(source, "root", source === noisyJpeg ? "image/jpeg" : "image/png");
const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, { body });
if (res.body.compressedCount !== 1) {
diff --git a/apps/server/src/services/image_provider.spec.ts b/apps/server/src/services/image_provider.spec.ts
index 3c05c514ae..5aa66fc321 100644
--- a/apps/server/src/services/image_provider.spec.ts
+++ b/apps/server/src/services/image_provider.spec.ts
@@ -25,6 +25,15 @@ let corruptPng: Uint8Array; // valid PNG signature but unreadable by jimp
let transparentPng: Uint8Array; // 600x400 noisy, every pixel half-transparent
let noisyJpeg: Uint8Array; // 600x400 noisy jpeg stored at high quality
let tinyJpeg: Uint8Array; // 8x8 jpeg that cannot get any smaller
+/**
+ * A photograph's shape rather than a photograph: smooth, spatially correlated colour over
+ * thousands of distinct values. PNG stores that poorly and JPEG stores it well, which is the
+ * relationship that makes converting worth doing at all.
+ *
+ * The `noisy` fixtures above are the opposite — pixel-level uncorrelated noise, which JPEG is bad
+ * at and which therefore cannot show conversion in a favourable light however high the quality.
+ */
+let photoPng: Uint8Array;
const svgBuffer = new TextEncoder().encode('<svg xmlns="http://www.w3.org/2000/svg"></svg>');
const garbageBuffer = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
const staticGif = Uint8Array.from(
@@ -73,6 +82,17 @@ beforeAll(async () => {
await makeImage(600, 400, { noisy: true }).getBuffer('image/jpeg', { quality: 100 })
);
tinyJpeg = new Uint8Array(await makeImage(8, 8).getBuffer('image/jpeg', { quality: 10 }));
+
+ const photo = new Jimp({ width: 600, height: 400, color: 0x000000ff });
+ for (let x = 0; x < 600; x++) {
+ for (let y = 0; y < 400; y++) {
+ const r = Math.round(128 + 127 * Math.sin(x / 40));
+ const g = Math.round(128 + 127 * Math.sin(y / 30));
+ const b = Math.round(128 + 127 * Math.sin((x + y) / 50));
+ photo.setPixelColor((((r << 24) | (g << 16) | (b << 8) | 0xff) >>> 0), x, y);
+ }
+ }
+ photoPng = new Uint8Array(await photo.getBuffer('image/png'));
}, 30000);
afterEach(() => {
@@ -239,8 +259,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,
- optimizePNG: true, quality: 75, ...overrides
+ resize: true, maxWidthHeight: 2000, reencode: true, pngHandling: "optimize",
+ quality: 75, conversionQuality: 85, ...overrides
};
}
@@ -263,47 +283,17 @@ describe('serverImageProvider.compressImage', () => {
expect(outcome.compressed).toBe(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 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('recompresses a JPEG on the lossy switch alone, converting switched off', async () => {
+ describe('what becomes of a PNG, one handling at a time', () => {
+ it('leaves it entirely alone on "keep", so only scaling can reach it', 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 the same PNG at its own size gains nothing besides.
- const outcome = await serverImageProvider.compressImage(
- noisyPng, request({ convertLossless: false, optimizePNG: false }));
+ noisyPng, request({ pngHandling: 'keep' }));
expect(outcome).toEqual({ compressed: false, reason: 'no-gain' });
});
- it('leaves a JPEG alone on the converting switch, which is not about lossy images', async () => {
+ it('scales it on "keep" but writes it back as the same kind of image', 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 })
- );
+ noisyPng, request({ maxWidthHeight: 100, pngHandling: 'keep' }));
expect(outcome).toMatchObject({ compressed: true, format: { ext: 'png', mime: 'image/png' } });
if (!outcome.compressed) return;
@@ -312,87 +302,58 @@ describe('serverImageProvider.compressImage', () => {
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 () => {
+ it('quantizes it on "optimize", staying a PNG and needing nothing to scale', async () => {
const outcome = await serverImageProvider.compressImage(
- noisyPng,
- request({ resize: false, maxWidthHeight: 100 })
- );
+ noisyPng, request({ pngHandling: 'optimize' }));
- expect(outcome).toMatchObject({ compressed: true, format: { ext: 'jpg', mime: 'image/jpeg' } });
+ expect(outcome).toMatchObject({ compressed: true, format: { ext: 'png', mime: 'image/png' } });
if (!outcome.compressed) return;
+ expect(outcome.buffer.byteLength).toBeLessThan(noisyPng.byteLength);
- // The bound is quoted and never measured against: nothing asked for it to be.
+ // Still 600x400: optimizing reaches an image already inside the bound.
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) => {
+ it('converts it on "jpeg", needing nothing to scale either', async () => {
const outcome = await serverImageProvider.compressImage(
- getBuffer(),
- request({
- resize: false, reencode: false, convertLossless: false, optimizePNG: false,
- maxWidthHeight: 10
- })
- );
+ photoPng, request({ pngHandling: 'jpeg' }));
- expect(outcome).toEqual({ compressed: false, reason: 'no-gain' });
- });
- });
-
- 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' } });
+ expect(outcome).toMatchObject({ compressed: true, format: { ext: 'jpg', mime: 'image/jpeg' } });
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 () => {
+ it('quantizes rather than converting a transparent image, JPEG having no alpha to keep', async () => {
+ // The fallback that makes "convert to JPEG" mean "make these as small as you can":
+ // answering a transparent image with nothing at all would be the perverse reading.
const outcome = await serverImageProvider.compressImage(
- noisyPng, request({ convertLossless: false }));
+ transparentPng, request({ pngHandling: 'jpeg' }));
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.buffer.byteLength).toBeLessThan(transparentPng.byteLength);
- expect(outcome).toMatchObject({ compressed: true, format: { ext: 'jpg', mime: 'image/jpeg' } });
+ const decoded = await Jimp.read(Buffer.from(outcome.buffer));
+ expect(decoded.bitmap.data.some((byte, i) => i % 4 === 3 && byte !== 255)).toBe(true);
});
- it('does not reach a JPEG, which is not a PNG to optimize', async () => {
+ it('converts one whose alpha channel is merely all-opaque', async () => {
+ // Detection reads the decoded pixels, so an alpha channel that happens to be all-255
+ // is correctly treated as no transparency at all rather than assumed dangerous.
+ const opaqueWithAlpha = new Uint8Array(
+ await Jimp.read(Buffer.from(photoPng)).then((image) => image.getBuffer('image/png'))
+ );
+
const outcome = await serverImageProvider.compressImage(
- noisyJpeg, request({ reencode: false, convertLossless: false }));
+ opaqueWithAlpha, request({ pngHandling: 'jpeg' }));
- expect(outcome).toEqual({ compressed: false, reason: 'no-gain' });
+ expect(outcome).toMatchObject({ compressed: true, format: { ext: 'jpg', mime: 'image/jpeg' } });
});
- it('scales and then quantizes, so both steps land on the stored image', async () => {
+ it('scales first and then quantizes, so both land on the stored image', async () => {
const outcome = await serverImageProvider.compressImage(
transparentPng, request({ maxWidthHeight: 100 }));
@@ -403,44 +364,66 @@ describe('serverImageProvider.compressImage', () => {
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 }));
+ it('never touches a JPEG, whichever handling is chosen', async () => {
+ for (const pngHandling of [ 'keep', 'optimize', 'jpeg' ] as const) {
+ const outcome = await serverImageProvider.compressImage(
+ noisyJpeg, request({ reencode: false, pngHandling }));
- expect(outcome).toEqual({ compressed: false, reason: 'transparent' });
+ expect(outcome).toEqual({ compressed: false, reason: 'no-gain' });
+ }
});
+ });
- it('still scales a transparent PNG down with nothing else switched on', async () => {
- const outcome = await serverImageProvider.compressImage(
- transparentPng,
- request({ maxWidthHeight: 100, optimizePNG: false })
- );
-
- expect(outcome).toMatchObject({ compressed: true, format: { ext: 'png', mime: 'image/png' } });
- if (!outcome.compressed) return;
+ describe('the two qualities', () => {
+ it('writes a converted PNG at the conversion quality, not the recompression one', async () => {
+ // The point of their being separate: converting a pristine original is a different
+ // trade from recompressing something already lossy, so one knob must not move both.
+ const converting = { pngHandling: 'jpeg' as const, quality: 20 };
+ const coarse = await serverImageProvider.compressImage(
+ photoPng, request({ ...converting, conversionQuality: 20 }));
+ const fine = await serverImageProvider.compressImage(
+ photoPng, request({ ...converting, conversionQuality: 90 }));
- // The point of the refusal above: the transparency has to survive the resize intact.
- const decoded = await Jimp.read(Buffer.from(outcome.buffer));
- expect(decoded.bitmap.width).toBe(100);
- expect(decoded.bitmap.data.some((byte, i) => i % 4 === 3 && byte !== 255)).toBe(true);
+ if (!coarse.compressed || !fine.compressed) throw new Error('expected both to compress');
+ expect(coarse.buffer.byteLength).toBeLessThan(fine.buffer.byteLength);
});
- it('converts a PNG whose alpha channel is fully opaque', async () => {
- // Detection reads the decoded pixels, so an alpha channel that happens to be all-255
- // is correctly treated as no transparency at all rather than assumed dangerous.
- const opaqueWithAlpha = new Uint8Array(
- await makeImage(600, 400, { noisy: true, alpha: 0xff }).getBuffer('image/png')
- );
+ it('writes a recompressed JPEG at the recompression quality, not the conversion one', async () => {
+ const recompressing = { conversionQuality: 20 };
+ const coarse = await serverImageProvider.compressImage(
+ noisyJpeg, request({ ...recompressing, quality: 20 }));
+ const fine = await serverImageProvider.compressImage(
+ noisyJpeg, request({ ...recompressing, quality: 80 }));
+
+ if (!coarse.compressed || !fine.compressed) throw new Error('expected both to compress');
+ expect(coarse.buffer.byteLength).toBeLessThan(fine.buffer.byteLength);
+ });
- const outcome = await serverImageProvider.compressImage(opaqueWithAlpha, request());
+ it('writes a scaled JPEG at the recompression quality with every re-encoding step off', async () => {
+ // Scaling has to write a JPEG back whatever the settings say, so that quality governs
+ // this too — which is why it is not nested under the recompression step.
+ const off = { reencode: false, pngHandling: 'keep' as const, maxWidthHeight: 300 };
+ const coarse = await serverImageProvider.compressImage(noisyJpeg, request({ ...off, quality: 20 }));
+ const fine = await serverImageProvider.compressImage(noisyJpeg, request({ ...off, quality: 80 }));
- expect(outcome).toMatchObject({ compressed: true, format: { ext: 'jpg', mime: 'image/jpeg' } });
+ 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, pngHandling: 'keep', maxWidthHeight: 10 })
+ );
+
+ expect(outcome).toEqual({ compressed: false, reason: 'no-gain' });
+ });
+
describe('lossy sources', () => {
it('recompresses a JPEG at the requested quality without resizing it', async () => {
const outcome = await serverImageProvider.compressImage(noisyJpeg, request({ quality: 40 }));
diff --git a/apps/server/src/services/image_provider.ts b/apps/server/src/services/image_provider.ts
index 5702944639..c7feafaf95 100644
--- a/apps/server/src/services/image_provider.ts
+++ b/apps/server/src/services/image_provider.ts
@@ -159,31 +159,25 @@ export const serverImageProvider: ImageProvider = {
const needsResize = request.resize && Math.max(width, height) > request.maxWidthHeight;
const isLossless = format.ext === "png";
- // 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));
-
- // 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.
+ // Only consulted where it changes the answer. JPEG has no alpha channel, so a transparent
+ // image cannot be converted — it is optimized instead, that being the best still available
+ // to it. The check reads the decoded pixels, so it is exact rather than a guess from the
+ // header, and it is skipped entirely where nothing is going to be converted anyway.
+ const convertible = isLossless && request.pngHandling === "jpeg" && !hasTransparency(image);
+
+ // What the image will be written back as. A JPEG can only ever be written back as one.
+ const toJpeg = !isLossless || convertible;
+ // A PNG that is staying a PNG is quantized unless it was to be left alone outright — which
+ // covers both `optimize` and a transparent image that `jpeg` could not take.
+ const quantize = isLossless && !toJpeg && request.pngHandling !== "keep";
+
+ // Whether re-encoding alone is worth doing to *this* image: a lossy source is recompressed
+ // if `reencode` says so, a lossless one when its handling asks for anything at all —
+ // rewriting a PNG as the same PNG at its own size gains nothing.
const worthReencoding = isLossless ? (toJpeg || quantize) : request.reencode;
if (!needsResize && !worthReencoding) {
- return {
- compressed: false,
- // 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"
- };
+ return { compressed: false, reason: "no-gain" };
}
if (needsResize) {
@@ -200,7 +194,10 @@ export const serverImageProvider: ImageProvider = {
// 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 });
+ // Converting a pristine original and recompressing an already-lossy one are different
+ // trades, so each is written at its own quality.
+ const quality = isLossless ? request.conversionQuality : request.quality;
+ result = await image.getBuffer("image/jpeg", { quality });
} else if (quantize) {
result = quantizePng(image, buffer.byteLength);
} else {
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.ts
index 0655f8968f..64cb954ec6 100644
--- a/packages/commons/src/lib/server_api.ts
+++ b/packages/commons/src/lib/server_api.ts
@@ -291,6 +291,11 @@ export interface SubtreeSizeResponse {
* Unlike the `compressImages` option, this is always a deliberate act by the user on one note or
* one image, so it runs whether or not automatic compression is switched on.
*/
+/** The three things that can become of a lossless image; see {@link ImageCompressionOptions}. */
+export const IMAGE_PNG_HANDLINGS = [ "keep", "optimize", "jpeg" ] as const;
+
+export type ImagePngHandling = (typeof IMAGE_PNG_HANDLINGS)[number];
+
export interface ImageCompressionOptions {
/**
* Whether an image larger than {@link maxWidthHeight} is scaled down to fit. On its own this
@@ -312,36 +317,38 @@ export interface ImageCompressionOptions {
*/
reencode?: boolean;
/**
- * 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.
+ * What is done with a lossless image — a PNG. Only ever one of the three, since a PNG either
+ * survives as it is, survives smaller, or stops being a PNG:
*
- * A PNG carrying transparency is never converted whatever this says, JPEG having no alpha
- * channel to keep it in — {@link optimizePNG} is what reaches those.
+ * - `keep` leaves it entirely alone; scaling is then the only thing that can reach it.
+ * - `optimize` reduces it to a palette and writes it back as a PNG. Lossy, but gently so — the
+ * saving comes from storing an index per pixel rather than 24-bit colour — and it keeps the
+ * alpha channel, so it reaches transparent images too.
+ * - `jpeg` re-encodes it as a JPEG at {@link conversionQuality}, which usually saves the most
+ * but costs the format. A transparent image cannot be converted, JPEG having no alpha channel
+ * to keep it in, so it is optimized instead: the best that can be done for it.
+ *
+ * Defaults to `optimize`, the choice that shrinks an image without changing what it is.
*/
- convertLossless?: boolean;
+ pngHandling?: ImagePngHandling;
/**
- * 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.
+ * JPEG quality, 10 to 100, used when recompressing an image that is *already* lossy — and when
+ * scaling one, which has to write a JPEG back whatever {@link reencode} says.
*
- * 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.
+ * Omitted, it falls back to the `imageJpegQuality` option (75 by default).
*/
- optimizePNG?: boolean;
+ quality?: number;
/**
- * JPEG quality, 10 to 100. Omitted, it falls back to the `imageJpegQuality` option (75 by
- * default).
+ * JPEG quality, 10 to 100, used when converting a lossless image — {@link pngHandling} of
+ * `jpeg` — rather than when recompressing one that was lossy already.
*
- * 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.
+ * Its own setting because the two are not the same trade. Converting is a one-time transition
+ * away from a pristine original, where every byte of quality given up is detail that genuinely
+ * was there; recompressing works on an image that has already been through an encoder once, so
+ * spending quality on it largely buys back nothing. Defaults higher than {@link quality}
+ * accordingly.
*/
- quality?: number;
+ conversionQuality?: 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
@@ -365,11 +372,6 @@ 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, 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"
/** Protected, with no protected session open to decrypt it. */
diff --git a/packages/trilium-core/src/services/image_compression.ts b/packages/trilium-core/src/services/image_compression.ts
index 00f75ce645..88ae7baba6 100644
--- a/packages/trilium-core/src/services/image_compression.ts
+++ b/packages/trilium-core/src/services/image_compression.ts
@@ -11,7 +11,7 @@
* recompressed belongs to the platform's {@link ImageProvider}.
*/
-import { getImageAttachmentTitle, type ImageCompressionItem, type ImageCompressionOptions, type ImageCompressionResponse, type ImageCompressionSkipReason } from "@triliumnext/commons";
+import { getImageAttachmentTitle, IMAGE_PNG_HANDLINGS, type ImageCompressionItem, type ImageCompressionOptions, type ImageCompressionResponse, type ImageCompressionSkipReason } from "@triliumnext/commons";
import becca from "../becca/becca.js";
import type BAttachment from "../becca/entities/battachment.js";
@@ -27,6 +27,14 @@ import { wrapStringOrBuffer } from "./utils/binary.js";
const MIN_QUALITY = 10;
const MAX_QUALITY = 100;
const DEFAULT_QUALITY = 75;
+
+/**
+ * Where converting a lossless image starts, deliberately above {@link DEFAULT_QUALITY}: this is a
+ * one-time transition away from a pristine original, so quality given up here is detail that was
+ * genuinely there. Recompressing an image that has already been through an encoder is the opposite
+ * trade — the loss is baked in, and spending quality on it buys back little.
+ */
+const DEFAULT_CONVERSION_QUALITY = 85;
/** A one-pixel bound is pointless but harmless; anything below it cannot be resized to. */
const MIN_MAX_WIDTH_HEIGHT = 1;
@@ -62,30 +70,31 @@ 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, optimizePNG, quality } = options;
+ const { resize, maxWidthHeight, reencode, pngHandling, quality, conversionQuality } = options;
if (maxWidthHeight !== undefined && (!Number.isInteger(maxWidthHeight) || maxWidthHeight < MIN_MAX_WIDTH_HEIGHT)) {
throw new ValidationError(`maxWidthHeight must be an integer of ${MIN_MAX_WIDTH_HEIGHT} or above.`);
}
- if (quality !== undefined && (!Number.isInteger(quality) || quality < MIN_QUALITY || quality > MAX_QUALITY)) {
- throw new ValidationError(`quality must be an integer between ${MIN_QUALITY} and ${MAX_QUALITY}.`);
- }
-
+ requireQuality(quality, "quality");
+ requireQuality(conversionQuality, "conversionQuality");
requireBoolean(resize, "resize");
requireBoolean(reencode, "reencode");
- requireBoolean(convertLossless, "convertLossless");
- requireBoolean(optimizePNG, "optimizePNG");
+
+ if (pngHandling !== undefined && !IMAGE_PNG_HANDLINGS.includes(pngHandling)) {
+ throw new ValidationError(`pngHandling must be one of: ${IMAGE_PNG_HANDLINGS.join(", ")}.`);
+ }
return {
- // 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.
+ // Every step defaults to acting: a request that named none of them asked for the images to
+ // be compressed, and narrowing that down is what the fields are for. For a PNG that means
+ // being made smaller without ceasing to be one.
resize: resize ?? true,
maxWidthHeight: maxWidthHeight ?? optionService.getOptionInt("imageMaxWidthHeight"),
reencode: reencode ?? true,
- convertLossless: convertLossless ?? true,
- optimizePNG: optimizePNG ?? true,
- quality: quality ?? defaultQuality()
+ pngHandling: pngHandling ?? "optimize",
+ quality: quality ?? defaultQuality(),
+ conversionQuality: conversionQuality ?? DEFAULT_CONVERSION_QUALITY
};
}
@@ -95,6 +104,12 @@ function requireBoolean(value: unknown, name: string) {
}
}
+function requireQuality(value: number | undefined, name: string) {
+ if (value !== undefined && (!Number.isInteger(value) || value < MIN_QUALITY || value > MAX_QUALITY)) {
+ throw new ValidationError(`${name} must be an integer between ${MIN_QUALITY} and ${MAX_QUALITY}.`);
+ }
+}
+
/**
* 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 —
diff --git a/packages/trilium-core/src/services/image_provider.ts b/packages/trilium-core/src/services/image_provider.ts
index dede4f68ba..7429d320a3 100644
--- a/packages/trilium-core/src/services/image_provider.ts
+++ b/packages/trilium-core/src/services/image_provider.ts
@@ -4,7 +4,7 @@
* Standalone uses simple format detection without compression.
*/
-import type { ImageCompressionSkipReason } from "@triliumnext/commons";
+import type { ImageCompressionSkipReason, ImagePngHandling } from "@triliumnext/commons";
export interface ImageFormat {
ext: string;
@@ -27,12 +27,12 @@ export interface ImageCompressionRequest {
maxWidthHeight: number;
/** 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;
- /** 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. */
+ /** What becomes of a lossless image (PNG): left alone, quantized in place, or converted. */
+ pngHandling: ImagePngHandling;
+ /** JPEG quality, 10 to 100, for recompressing or scaling an already-lossy image. */
quality: number;
+ /** JPEG quality, 10 to 100, for converting a lossless image. */
+ conversionQuality: number;
}
export type ImageCompressionOutcome =