1 [![Build Status](https://travis-ci.org/lukeapage/pngjs.svg?branch=master)](https://travis-ci.org/lukeapage/pngjs) [![Build status](https://ci.appveyor.com/api/projects/status/tb8418jql1trkntd/branch/master?svg=true)](https://ci.appveyor.com/project/lukeapage/pngjs2/branch/master) [![Coverage Status](https://coveralls.io/repos/lukeapage/pngjs2/badge.svg?branch=master&service=github)](https://coveralls.io/github/lukeapage/pngjs2?branch=master) [![npm version](https://badge.fury.io/js/pngjs.svg)](http://badge.fury.io/js/pngjs)
6 [![Greenkeeper badge](https://badges.greenkeeper.io/lukeapage/pngjs.svg)](https://greenkeeper.io/)
7 Simple PNG encoder/decoder for Node.js with no dependencies.
9 Based on the original [pngjs](https://github.com/niegowski/node-pngjs) with the follow enhancements.
11 * Support for reading 1,2,4 & 16 bit files
12 * Support for reading interlace files
13 * Support for reading `tTRNS` transparent colours
14 * Support for writing colortype 0 (grayscale), colortype 2 (RGB), colortype 4 (grayscale alpha) and colortype 6 (RGBA)
15 * Sync interface as well as async
16 * API compatible with pngjs and node-pngjs
18 Known lack of support for:
20 * Extended PNG e.g. Animation
21 * Writing in colortype 3 (indexed color)
24 * [Requirements](#requirements)
25 * [Comparison Table](#comparison-table)
27 * [Installation](#installation)
30 * [Async API](#async-api)
31 * [Sync API](#sync-api)
32 * [Changelog](#changelog)
37 * Node.js v4 (use older v2.3.0 for 0.10/0.12/iojs support)
42 Name | Forked From | Sync | Async | 16 Bit | 1/2/4 Bit | Interlace | Gamma | Encodes | Tested
43 ---------|--------------|------|-------|--------|-----------|-----------|-------|---------|--------
44 pngjs | | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes
45 node-png | pngjs | No | Yes | No | No | No | Hidden| Yes | Manual
46 png-coder| pngjs | No | Yes | Yes | No | No | Hidden| Yes | Manual
47 pngparse | | No | Yes | No | Yes | No | No | No | Yes
48 pngparse-sync | pngparse| Yes | No | No | Yes | No | No | No | Yes
49 png-async| | No | Yes | No | No | No | No | Yes | Yes
50 png-js | | No | Yes | No | No | No | No | No | No
53 Native C++ node decoders:
55 * png-sync (sync version of above)
62 Tested using [PNG Suite](http://www.schaik.com/pngsuite/). We read every file into pngjs, output it in standard 8bit colour, synchronously and asynchronously, then compare the original with the newly saved images.
64 To run the tests, fetch the repo (tests are not distributed via npm) and install with `npm i`, run `npm test`.
66 The only thing not converted is gamma correction - this is because multiple vendors will do gamma correction differently, so the tests will have different results on different browsers.
68 In addition we use a tolerance of 3 for 16 bit images in PhantomJS because PhantomJS seems to have non-compliant rules for downscaling 16 bit images.
73 $ npm install pngjs --save
78 The package has been build with a [Browserify](browserify.org) version (`npm run browserify`) and you can use the browser version by including in your code:
81 import { PNG } from 'pngjs/browser';
87 var fs = require('fs'),
88 PNG = require('pngjs').PNG;
90 fs.createReadStream('in.png')
94 .on('parsed', function() {
96 for (var y = 0; y < this.height; y++) {
97 for (var x = 0; x < this.width; x++) {
98 var idx = (this.width * y + x) << 2;
101 this.data[idx] = 255 - this.data[idx];
102 this.data[idx+1] = 255 - this.data[idx+1];
103 this.data[idx+2] = 255 - this.data[idx+2];
105 // and reduce opacity
106 this.data[idx+3] = this.data[idx+3] >> 1;
110 this.pack().pipe(fs.createWriteStream('out.png'));
113 For more examples see `examples` folder.
118 As input any color type is accepted (grayscale, rgb, palette, grayscale with alpha, rgb with alpha) but 8 bit per sample (channel) is the only supported bit depth. Interlaced mode is not supported.
121 `PNG` is readable and writable `Stream`.
125 - `width` - use this with `height` if you want to create png from scratch
126 - `height` - as above
127 - `checkCRC` - whether parser should be strict about checksums in source stream (default: `true`)
128 - `deflateChunkSize` - chunk size used for deflating data chunks, this should be power of 2 and must not be less than 256 and more than 32*1024 (default: 32 kB)
129 - `deflateLevel` - compression level for deflate (default: 9)
130 - `deflateStrategy` - compression strategy for deflate (default: 3)
131 - `deflateFactory` - deflate stream factory (default: `zlib.createDeflate`)
132 - `filterType` - png filtering method for scanlines (default: -1 => auto, accepts array of numbers 0-4)
133 - `colorType` - the output colorType - see constants. 0 = grayscale, no alpha, 2 = color, no alpha, 4 = grayscale & alpha, 6 = color & alpha. Default currently 6, but in the future may calculate best mode.
134 - `inputColorType` - the input colorType - see constants. Default is 6 (RGBA)
135 - `bitDepth` - the bitDepth of the output, 8 or 16 bits. Input data is expected to have this bit depth.
136 16 bit data is expected in the system endianness (Default: 8)
137 - `inputHasAlpha` - whether the input bitmap has 4 bytes per pixel (rgb and alpha) or 3 (rgb - no alpha).
138 - `bgColor` - an object containing red, green, and blue values between 0 and 255
139 that is used when packing a PNG if alpha is not to be included (default: 255,255,255)
143 `function(metadata) { }`
144 Image's header has been parsed, metadata contains this information:
145 - `width` image size in pixels
146 - `height` image size in pixels
147 - `palette` image is paletted
148 - `color` image is not grayscale
149 - `alpha` image contains alpha channel
150 - `interlace` image is interlaced
155 Input image has been completely parsed, `data` is complete and ready for modification.
159 `function(error) { }`
162 ### png.parse(data, [callback])
163 Parses PNG file data. Can be `String` or `Buffer`. Alternatively you can stream data to instance of PNG.
165 Optional `callback` is once called on `error` or `parsed`. The callback gets
166 two arguments `(err, data)`.
168 Returns `this` for method chaining.
172 new PNG({ filterType:4 }).parse( imageData, function(error, data)
174 console.log(error, data)
179 Starts converting data to PNG file Stream.
181 Returns `this` for method chaining.
184 ### png.bitblt(dst, sx, sy, w, h, dx, dy)
185 Helper for image manipulation, copies a rectangle of pixels from current (i.e. the source) image (`sx`, `sy`, `w`, `h`) to `dst` image (at `dx`, `dy`).
187 Returns `this` for method chaining.
189 For example, the following code copies the top-left 100x50 px of `in.png` into dst and writes it to `out.png`:
191 var dst = new PNG({width: 100, height: 50});
192 fs.createReadStream('in.png')
194 .on('parsed', function() {
195 this.bitblt(dst, 0, 0, 100, 50, 0, 0);
196 dst.pack().pipe(fs.createWriteStream('out.png'));
200 ### Property: adjustGamma()
201 Helper that takes data and adjusts it to be gamma corrected. Note that it is not 100% reliable with transparent colours because that requires knowing the background colour the bitmap is rendered on to.
203 In tests against PNG suite it compared 100% with chrome on all 8 bit and below images. On IE there were some differences.
205 The following example reads a file, adjusts the gamma (which sets the gamma to 0) and writes it out again, effectively removing any gamma correction from the image.
208 fs.createReadStream('in.png')
210 .on('parsed', function() {
212 this.pack().pipe(fs.createWriteStream('out.png'));
217 Width of image in pixels
221 Height of image in pixels
225 Buffer of image pixel data. Every pixel consists 4 bytes: R, G, B, A (opacity).
229 Gamma of image (0 if not specified)
231 ## Packing a PNG and removing alpha (RGBA to RGB)
233 When removing the alpha channel from an image, there needs to be a background color to correctly
234 convert each pixel's transparency to the appropriate RGB value. By default, pngjs will flatten
235 the image against a white background. You can override this in the options:
238 var fs = require('fs'),
239 PNG = require('pngjs').PNG;
241 fs.createReadStream('in.png')
250 .on('parsed', function() {
251 this.pack().pipe(fs.createWriteStream('out.png'));
259 ### PNG.sync.read(buffer)
261 Take a buffer and returns a PNG image. The properties on the image include the meta data and `data` as per the async API above.
264 var data = fs.readFileSync('in.png');
265 var png = PNG.sync.read(data);
268 ### PNG.sync.write(png)
270 Take a PNG image and returns a buffer. The properties on the image include the meta data and `data` as per the async API above.
273 var data = fs.readFileSync('in.png');
274 var png = PNG.sync.read(data);
275 var options = { colorType: 6 };
276 var buffer = PNG.sync.write(png, options);
277 fs.writeFileSync('out.png', buffer);
280 ### PNG.adjustGamma(src)
282 Adjusts the gamma of a sync image. See the async adjustGamma.
285 var data = fs.readFileSync('in.png');
286 var png = PNG.sync.read(data);
287 PNG.adjustGamma(png);
294 ### 3.4.0 - 09/03/2019
296 - Include whether the png has alpha in the meta data
297 - emit an error if the image is truncated instead of hanging
298 - Add a browserified version
299 - speed up some mapping functions
301 ### 3.3.3 - 19/04/2018
303 - Real fix for node 9
305 ### 3.3.2 - 16/02/2018
309 ### 3.3.1 - 15/11/2017
311 - Bugfixes and removal of es6
315 - Add writing 16 bit channels and support for grayscale input
317 ### 3.2.0 - 30/04/2017
319 - Support for encoding 8-bit grayscale images
321 ### 3.1.0 - 30/04/2017
322 - Support for pngs with zlib chunks that are malformed after valid data
324 ### 3.0.1 - 16/02/2017
325 - Fix single pixel pngs
327 ### 3.0.0 - 03/08/2016
328 - Drop support for node below v4 and iojs. Pin to 2.3.0 to use with old, unsupported or patched node versions.
330 ### 2.3.0 - 22/04/2016
331 - Support for sync in node 0.10
333 ### 2.2.0 - 04/12/2015
335 - Fix newfile example
336 - Correct comparison table
338 ### 2.1.0 - 28/10/2015
339 - rename package to pngjs
340 - added 'bgColor' option
342 ### 2.0.0 - 08/10/2015
344 - *breaking change* - bitblt on the png prototype now doesn't take a unused, unnecessary src first argument
346 ### 1.2.0 - 13/09/2015
347 - support passing colorType to write PNG's and writing bitmaps without alpha information
349 ### 1.1.0 - 07/09/2015
350 - support passing a deflate factory for controlled compression
352 ### 1.0.2 - 22/08/2015
353 - Expose all PNG creation info
355 ### 1.0.1 - 21/08/2015
356 - Fix non square interlaced files
358 ### 1.0.0 - 08/08/2015
361 - maintainability refactorings
362 - async API - exceptions in reading now emit warnings
363 - documentation improvement - sync api now documented, adjustGamma documented
364 - breaking change - gamma chunk is now written. previously a read then write would destroy gamma information, now it is persisted.
366 ### 0.0.3 - 03/08/2015
367 - Error handling fixes
368 - ignore files for smaller npm footprint
370 ### 0.0.2 - 02/08/2015
371 - Bugfixes to interlacing, support for transparent colours
373 ### 0.0.1 - 02/08/2015
374 - Initial release, see pngjs for older changelog.
381 Permission is hereby granted, free of charge, to any person obtaining a copy
382 of this software and associated documentation files (the "Software"), to deal
383 in the Software without restriction, including without limitation the rights
384 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
385 copies of the Software, and to permit persons to whom the Software is
386 furnished to do so, subject to the following conditions:
388 The above copyright notice and this permission notice shall be included in
389 all copies or substantial portions of the Software.
391 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
392 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
393 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
394 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
395 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
396 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN