What is png-js?
The png-js npm package is a JavaScript library for decoding PNG images. It allows you to read and manipulate PNG image data directly in JavaScript, making it useful for applications that need to process image data on the client or server side.
What are png-js's main functionalities?
Decoding PNG Image
This feature allows you to decode a PNG image and get the raw pixel data as a Uint8Array. This can be useful for image processing tasks such as filtering, analysis, or conversion to other formats.
const PNG = require('png-js');
PNG.decode('path/to/image.png', function(pixels) {
console.log(pixels); // Uint8Array of pixel data
});
Reading PNG Metadata
This feature allows you to read the metadata of a PNG image, such as its width and height. This can be useful for applications that need to know the dimensions of an image before processing it.
const PNG = require('png-js');
const png = new PNG('path/to/image.png');
png.decode(function(pixels) {
console.log(png.width, png.height); // Dimensions of the image
});
Other packages similar to png-js
pngjs
The pngjs package is another library for reading and writing PNG files in pure JavaScript. It offers more advanced features such as support for different color types and interlacing, making it a more versatile option compared to png-js.
node-png
The node-png package provides a simple interface for reading and writing PNG files. It is similar to png-js but offers additional features like support for alpha transparency and palette-based images.
png-async
The png-async package is designed for asynchronous reading and writing of PNG files. It provides a more modern API with Promises and async/await support, making it easier to integrate into modern JavaScript applications compared to png-js.
png.js
A PNG decoder in JS for the canvas element or Node.js.
Browser Usage
Simply include png.js and zlib.js on your HTML page, create a canvas element, and call PNG.load to load an image.
<canvas></canvas>
<script src="zlib.js"></script>
<script src="png.js"></script>
<script>
var canvas = document.getElementsByTagName('canvas')[0];
PNG.load('some.png', canvas);
</script>
The source code for the browser version resides in png.js
and also supports loading and displaying animated PNGs.
Node.js Usage
Install the module using npm
sudo npm install png-js
Require the module and decode a PNG
var PNG = require('png-js');
PNG.decode('some.png', function(pixels) {
// pixels is a 1d array (in rgba order) of decoded pixel data
});
You can also call PNG.load
if you want to load the PNG (but not decode the pixels) synchronously. If you already
have the PNG data in a buffer, simply use new PNG(buffer)
. In both of these cases, you need to call png.decode
yourself which passes your callback the decoded pixels as a buffer. If you already have a buffer you want the pixels
copied to, call copyToImageData
with your buffer and the decoded pixels as returned from decodePixels
.