@imgsolve/compress-to-target
v1.0.0
Published
Compress browser images toward a target file size.
Maintainers
Readme
@imgsolve/compress-to-target
A small, dependency-free browser utility that compresses JPEG, PNG, or WebP images toward a maximum target file size. Processing happens locally in the user's browser with Canvas.
Installation
npm install @imgsolve/compress-to-targetUsage
import { compressToTargetKB } from "@imgsolve/compress-to-target";
const input = document.querySelector("input[type=file]");
input.addEventListener("change", async () => {
const file = input.files[0];
const compressed = await compressToTargetKB(file, 100, {
type: "image/jpeg"
});
const downloadUrl = URL.createObjectURL(compressed);
const link = document.createElement("a");
link.href = downloadUrl;
link.download = "compressed.jpg";
link.click();
URL.revokeObjectURL(downloadUrl);
});You can also specify the target in bytes:
import { compressToTarget } from "@imgsolve/compress-to-target";
const result = await compressToTarget(file, {
targetBytes: 200 * 1024,
type: "image/webp",
maxWidth: 1920,
maxHeight: 1080
});API
compressToTarget(file, options)
file: an imageBloborFiletargetBytes: maximum desired output size in bytestype:image/jpegorimage/webpmaxWidthandmaxHeight: optional dimension limitsminQualityandmaxQuality: optional encoder quality rangeattempts: optional number of quality-search attempts
Returns a Promise<Blob>. Exact byte size is not guaranteed because browser
encoders and image content vary; the function searches for a useful result at
or below the requested maximum and reduces dimensions when necessary.
Try ImgSolve online
Need a ready-to-use tool without writing code?
Compress, convert, and resize images with ImgSolve
Browser support
The package requires a modern browser with Canvas, Blob, and
createImageBitmap support. It is not intended for direct Node.js processing.
License
MIT
