light-image-compress
v1.0.1
Published
Compress image buffers toward a target file size using JPEG or WebP
Maintainers
Readme
simple-image-compress
Compress image buffers toward a target file size (e.g. ~1 MB → ~200 KB).
Input and output are buffers — no file paths in the API.
Install
npm install simple-image-compress
# or
yarn add simple-image-compressRequires Node.js 18+.
Usage
const fs = require("fs");
const { compressImage } = require("simple-image-compress");
const imageBuffer = fs.readFileSync("./photo.jpg");
const result = await compressImage(imageBuffer, {
targetSizeBytes: 200 * 1024,
format: "jpeg",
});
fs.writeFileSync("./photo-small.jpg", result.data);
console.log(result.sizeBytes, result.quality, result.width, result.height);Result
| Field | Description |
|-------|-------------|
| data | Compressed image Buffer |
| sizeBytes | Size of data |
| quality | JPEG/WebP quality used (1–100) |
| width, height | Output dimensions |
| format | "jpeg" or "webp" |
Options
| Option | Default | Description |
|--------|---------|-------------|
| targetSizeBytes | 204800 | Target file size (~200 KB) |
| format | "jpeg" | "jpeg" or "webp" |
| toleranceRatio | 0.1 | Allow up to 10% over target before shrinking further |
| minScale | 0.25 | Minimum dimension scale when quality alone is not enough |
| maxWidth, maxHeight | — | Optional size limits |
How it works
- Resize (if
maxWidth/maxHeightset) and binary-search quality to fit under target. - If still too large, shrink dimensions by 15% and retry until within tolerance or
minScaleis reached.
Test
yarn test