Home

Awesome

UPNG.js

A small, fast and advanced PNG / APNG encoder and decoder. It is the main PNG engine for Photopea image editor.

Download and include the UPNG.js file in your code.

Encoder

UPNG.js supports APNG and the interface expects "frames". Regular PNG is just a single-frame animation (single-item array).

UPNG.encode(imgs, w, h, cnum, [dels])

UPNG.js can do a lossy minification of PNG files, similar to TinyPNG and other tools. It performed quantization with k-means algorithm in the past, but now we use K-d trees.

Lossy compression is allowed by the last parameter cnum. Set it to zero for a lossless compression, or write the number of allowed colors in the image. Smaller values produce smaller files. Or just use 0 for lossless / 256 for lossy.

// Read RGBA from canvas and encode with UPNG
var dta = ctx.getImageData(0,0,200,300).data;  // ctx is Context2D of a Canvas
//  dta = new Uint8Array(200 * 300 * 4);       // or generate pixels manually
var png = UPNG.encode([dta.buffer], 200, 300, 0);   console.log(new Uint8Array(png));

UPNG.encodeLL(imgs, w, h, cc, ac, depth, [dels]) - low-level encode

This function does not do any optimizations, it just stores what you give it. There are two cases when it is useful:

Decoder

Supports all color types (including Grayscale and Palettes), all channel depths (1, 2, 4, 8, 16), interlaced images etc. Opens PNGs which other libraries can not open (tested with PngSuite).

UPNG.decode(buffer)

PNG files may have a various number of channels and a various color depth. The interpretation of data depends on the current color type and color depth (see the PNG specification).

UPNG.toRGBA8(img)

Example

var img  = UPNG.decode(buff);        // put ArrayBuffer of the PNG file into UPNG.decode
var rgba = UPNG.toRGBA8(img)[0];     // UPNG.toRGBA8 returns array of frames, size: width * height * 4 bytes.

PNG format uses the Inflate algorithm. Right now, UPNG.js calls Pako.js for the Inflate and Deflate method.

Quantizer

UPNG.js contains a very good Quantizer of 4-component 8-bit vectors (i.e. pixels). It can be used to generate nice color palettes (e.g. Photopea uses UPNG.js to make palettes for GIF images).

Quantization consists of two important steps: Finding a nice palette and Finding the closest color in the palette for each sample (non-trivial for large palettes). UPNG perfroms both steps.

var res  = UPNG.quantize(data, psize);

The result object "res" has following properties:

FAQ