picowebpjs
v1.0.0
Published
Pure-TypeScript WebP encoder: writes VP8 lossy WebP (with alpha and ICC) from PNG, baseline JPEG, BMP or raw pixels. No native bindings, no WASM, no libwebp.
Maintainers
Readme
PicoWebPJS
Convert PNG, baseline JPEG, BMP, or raw RGB pixels to WebP using JavaScript. PicoWebPJS includes its own image readers and encoder, with no runtime dependencies, native bindings, or WebAssembly. It works in Node.js and modern browsers, including Web Workers.
The output uses lossy compression for colour and lossless compression for transparency. ICC colour profiles are preserved when present.
This is a TypeScript port of PicoWebP, by NikoCodes.
Install
npm install picowebpjsThe Node.js API and CLI require Node 18 or later. Both ES modules and CommonJS are supported, with TypeScript declarations included.
Convert a file
From the command line:
npx picowebpjs photo.jpg photo.webp --quality=80
npx picowebpjs image.png image.webp --quality=80Or in a Node.js ES module, such as convert.mjs:
import { writeFileSync } from 'node:fs';
import { Vp8LossyEncoder } from 'picowebpjs';
import { NodeImageInput } from 'picowebpjs/node';
const pixels = NodeImageInput.pixels('photo.jpg');
const encoder = Vp8LossyEncoder.fromQuality(80);
encoder.alphaPlane = pixels.alpha;
encoder.iccProfile = pixels.icc;
const { webp } = encoder.encode(pixels.rgb, pixels.w, pixels.h);
writeFileSync('photo.webp', webp);Quality ranges from 0 to 100. Higher values generally produce larger files
with more detail. Even at quality 100, the colour output is lossy.
For CommonJS, replace the imports with:
const { Vp8LossyEncoder } = require('picowebpjs');
const { NodeImageInput } = require('picowebpjs/node');Use it in a browser
ImageInput accepts bytes instead of a file path. For example, with a browser
File object:
import { ImageInput, Vp8LossyEncoder } from 'picowebpjs';
async function encodeFile(file) {
const bytes = new Uint8Array(await file.arrayBuffer());
const pixels = ImageInput.pixels(bytes, file.name);
const encoder = Vp8LossyEncoder.fromQuality(80);
encoder.alphaPlane = pixels.alpha;
encoder.iccProfile = pixels.icc;
const { webp } = encoder.encode(pixels.rgb, pixels.w, pixels.h);
return new Blob([webp], { type: 'image/webp' });
}Decoding and encoding are synchronous. Put this work in a Web Worker to keep the page responsive while processing larger images. The browser example shows how, using the built ES modules directly without a bundler.
Supported inputs
| Input | Support | | --- | --- | | PNG | All colour types and bit depths, including interlacing, palettes, transparency, and ICC profiles | | Baseline JPEG | 8-bit greyscale and YCbCr, including restart markers, separate scans, and ICC profiles | | BMP | 1, 4, 8, 16, 24, and 32-bit images; RLE4/RLE8; channel masks; embedded V5 ICC profiles | | Raw RGB | Packed 8-bit RGB, with an optional alpha plane | | Progressive JPEG | Requires a custom platform decoder | | WebP | Skipped by default; re-encoding requires a custom platform decoder | | GIF, TIFF, raw YUV | Not supported |
The format is detected from the file contents, so renaming a file does not change how it is handled.
Raw pixels
Pass a Uint8Array containing three bytes per pixel: red, green, and blue, from
left to right and top to bottom. Its length must be exactly width × height × 3.
import { Vp8LossyEncoder } from 'picowebpjs';
const width = 16;
const height = 16;
const rgb = new Uint8Array(width * height * 3).fill(153);
const encoder = Vp8LossyEncoder.fromQuality(80);
const { webp } = encoder.encode(rgb, width, height);For transparency, set encoder.alphaPlane to a separate Uint8Array with one
byte per pixel: 0 for transparent and 255 for opaque.
Each dimension must be a whole number between 1 and 16,383. Large images need substantial memory, so choose an input-size limit suitable for your application.
Existing WebP files
ImageInput.pixels() throws SkippedInput when the input is already a WebP:
import { ImageInput, SkippedInput } from 'picowebpjs';
try {
const pixels = ImageInput.pixels(bytes, 'image.webp');
// Encode pixels here.
} catch (error) {
if (error instanceof SkippedInput) {
console.log(error.reason());
} else {
throw error;
}
}ImageInput.isWebp(bytes) checks the format without decoding pixels. Like the
other readers, it throws if the input cannot be recognised as an image.
Custom decoders
For progressive JPEG or WebP input, register an ImageInput.platformDecoder
with a name and a synchronous decode(bytes, type, meta) method. It must return
{ w, h, rgb }, optionally including alpha and icc, or null if it cannot
decode the input. These buffers use the same layout as the raw-pixel API.
Set ImageInput.skipWebp = false to allow WebP input. Set
ImageInput.preferBundled = true to try the built-in readers first, or
ImageInput.platformDecoderAvailable = false to disable the custom decoder.
BMP always uses the built-in reader.
Browser APIs such as createImageBitmap() are asynchronous, so they cannot be
used directly as this hook. Decode with them first, then pass the resulting
pixels to the encoder.
CLI options
npx picowebpjs input.png output.webp --quality=80 --json
npx picowebpjs pixels.raw output.webp --rgb=1200x800 --alpha-plane=alpha.raw
npx picowebpjs --help| Option | Description |
| --- | --- |
| --quality=0..100 | Encoding quality; defaults to 80 |
| --rgb=WxH | Read headerless RGB pixels |
| --alpha-plane=FILE | Read one alpha byte per pixel; requires --rgb |
| --alpha=keep\|flatten\|fail | Keep transparency, discard it, or reject input with an alpha channel; defaults to keep |
| --alpha-filter=0..3 | Choose an alpha prediction filter; selected automatically when omitted |
| --icc=FILE | Use this ICC profile instead of the source profile |
| --no-icc | Omit the source ICC profile |
| --json | Print a JSON report with dimensions, output size, and timing |
| --dump-yuv=FILE | Write the padded Y, U, and V planes for inspection |
--alpha=flatten discards transparency; it does not composite the image onto
a background colour. Composite the pixels before encoding if you need that.
The CLI also accepts a positional VP8 quantiser index (0..127) after the output
path. This overrides --quality; lower quantiser values mean higher quality.
Exit codes are 0 for success, 1 for an error, 3 when --alpha=fail rejects
the image, and 4 when an existing WebP is skipped. A skipped input produces no
output file.
The compatibility flags --bundled, --no-gd, and --reencode-webp are also
accepted. The standalone CLI does not include a platform decoder, so
--reencode-webp alone cannot convert WebP input.
Performance and limitations
PicoWebPJS is useful when you need WebP encoding without a native library or a WASM asset. A native encoder such as libwebp will generally be faster. The same quality number can also produce different file sizes and visual quality across encoders, so compare the results on your own images.
A few limitations to keep in mind:
- The package produces lossy WebP images.
Vp8lEncoderis a helper for alpha compression, not a general-purpose lossless image API. - ICC profiles are copied, but EXIF metadata is not. EXIF orientation is not applied; rotate or mirror your input beforehand if needed.
- The regular encode path keeps the whole image in memory and blocks the calling thread until it finishes.
For less CPU work, try encoder.adaptProbs = false or the CLI's
--no-adapt-probs. Other tuning options include --no-bpred, --no-rd,
--prune=N, --rd-lambda=N, --trellis, and --no-skip.
Encoding in stages
For queues that need to pause and resume work, PlaneStore from
picowebpjs/node can stage image planes on disk. The encoder processes them in
bands using beginBand(), encodeRowRange(), and finishFrame().
exportState() and importState() let a job resume in another process;
stateToJson() and stateFromJson() handle serialisation.
See the queue example for the complete sequence, including probability adaptation, alpha, and ICC profiles. It checks that the staged output matches a single encode. Staging still requires the decoded image in memory initially, and it does not make encoding faster.
Development
From a checkout of this repository:
npm ci
npm test
npm run typecheckThe tests compare encoded files and decoded pixels with fixtures from the PHP
implementation. They also cover malformed inputs, the CLI, staged encoding,
ESM/CommonJS imports, and TypeScript consumers. If dwebp is on your PATH,
the suite uses it to independently check the generated WebP files and alpha
round-trips. See the fixture notes for details.
Run the examples or benchmark with:
npm run example:encode -- photo.jpg photo.webp
npm run example:chunked -- photo.jpg /tmp/picowebpjs-work
npm run bench -- --size=1200x800 --repeat=3These commands build the required files first. The benchmark can also compare
output with libwebp when cwebp and dwebp are installed.
