Files
reimage/libReimage.js
2026-10-06 23:17:06 -05:00

131 lines
3.4 KiB
JavaScript

const fs = require('fs');
const sharp = require('sharp');
const defaultOptions = Object.freeze({
format: 'jpg',
outputDpi: 300,
// JPEG defaults are explicit so our output behavior does not drift if
// Sharp changes one of its own defaults in a future release.
jpegQuality: 85,
jpegChromaSubsampling: '4:2:0',
jpegProgressive: false,
jpegOptimiseCoding: true,
});
module.exports = function libReimage(globalOptions = {}) {
const options = {
...defaultOptions,
...globalOptions,
};
function getOptions(localOptions = {}) {
return {
...options,
...localOptions,
};
}
function jpegOptions(effectiveOptions) {
return {
quality: effectiveOptions.jpegQuality,
chromaSubsampling: effectiveOptions.jpegChromaSubsampling,
progressive: effectiveOptions.jpegProgressive,
optimiseCoding: effectiveOptions.jpegOptimiseCoding,
};
}
function asSharp(img) {
if (img && typeof img.clone === 'function' && typeof img.metadata === 'function') {
return img.clone();
}
return sharp(img);
}
async function isImage(file) {
try {
await sharp(file).metadata();
return true;
} catch {
return false;
}
}
async function load(file) {
return fs.promises.readFile(file);
}
/**
* Intentionally materialize the image as JPEG BEFORE resizing it.
*
* This is not merely output-format selection. For photo-style images we
* deliberately want JPEG's lossy compression to simplify/smooth fine image
* detail before resampling. The returned Buffer contains actual JPEG bytes,
* so later resize operations cannot optimize this encode/decode boundary away.
*
* Do not collapse this operation into resizeMegaPixel() or saveAs().
*/
async function forceJpg(img, localOptions = {}) {
const effectiveOptions = getOptions(localOptions);
return asSharp(img)
.jpeg(jpegOptions(effectiveOptions))
.toBuffer();
}
async function resizeMegaPixel(img, megapixels) {
if (!Number.isFinite(megapixels) || megapixels <= 0) {
throw new Error(`megapixels must be a positive number; received ${megapixels}`);
}
const pipeline = asSharp(img);
const metadata = await pipeline.metadata();
if (!metadata.width || !metadata.height) {
throw new Error('Cannot resize image without width and height metadata.');
}
const targetPixels = megapixels * 1_000_000;
const aspectRatio = metadata.width / metadata.height;
const width = Math.max(1, Math.round(Math.sqrt(targetPixels * aspectRatio)));
const height = Math.max(1, Math.round(targetPixels / width));
return pipeline.resize(width, height);
}
async function toGrayscale(img) {
return asSharp(img).grayscale();
}
async function saveAs(img, destination, localOptions = {}) {
const effectiveOptions = getOptions(localOptions);
let pipeline = asSharp(img);
if (effectiveOptions.outputDpi) {
pipeline = pipeline.withMetadata({ density: effectiveOptions.outputDpi });
}
const format = String(effectiveOptions.format).toLowerCase();
if (format === 'jpg' || format === 'jpeg') {
pipeline = pipeline.jpeg(jpegOptions(effectiveOptions));
} else {
pipeline = pipeline.toFormat(format);
}
return pipeline.toFile(destination);
}
return {
isImage,
load,
forceJpg,
resizeMegaPixel,
toGrayscale,
saveAs,
};
};