Simple PNG encoder/decoder for Node.js and browsers with no dependencies.
A fork from pngjs. The
package is prepared for the browser and there are some changes in the exports. The
pngjs
has been extended with the following enhancements:
skipRescale
that allows retrieval of 16-bit data if input was 16-bitgrayscaleData
for retrieving the grayscale bitmap (note ignores alpha channel and caches the grayscale conversion†)propData
for retrieving the proportional values (note ignores alpha channel and caches the proportional conversion†)
† If you manipulate the data
property of the object directly the conversions will not be recalculated due to the cache.
The pngjs had the follow enhancements compared to the original:
- Support for reading 1, 2, 4 & 16 bit files
- Support for reading interlace files
- Support for reading
tTRNS
transparent colours - Support for writing colortype 0 (grayscale), colortype 2 (RGB), colortype 4 (grayscale alpha) and colortype 6 (RGBA)
- Sync interface as well as async
- API compatible with pngjs and node-pngjs
Known lack of support for:
- Extended PNG e.g. Animation
- Writing in colortype 3 (indexed color)
- Node.js v10 or later
Name | Forked From | Sync | Async | 16 Bit | 1/2/4 Bit | Interlace | Gamma | Encodes | Tested |
---|---|---|---|---|---|---|---|---|---|
pngjs3 | pngjs | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
pngjs | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | |
node-png | pngjs | No | Yes | No | No | No | Hidden | Yes | Manual |
png-coder | pngjs | No | Yes | Yes | No | No | Hidden | Yes | Manual |
pngparse | No | Yes | No | Yes | No | No | No | Yes | |
pngparse-sync | pngparse | Yes | No | No | Yes | No | No | No | Yes |
png-async | No | Yes | No | No | No | No | Yes | Yes | |
png-js | No | Yes | No | No | No | No | No | No |
Native C++ node decoders:
- png
- png-sync (sync version of above)
- pixel-png
- png-img
Tested using PNG Suite. We read every file into pngjs, output it in standard 8bit colour, synchronously and asynchronously, then compare the original with the newly saved images.
To run the tests, fetch the repo (tests are not distributed via npm) and install with npm i
, run npm test
.
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.
$ npm install pngjs3 --save
or with yarn
$ yarn add pngjs3
The package has been build with browser support using browserify-zlib
instead of NodeJS' zlib
.
import fs from 'fs';
import PNG from 'pngjs3';
fs.createReadStream('in.png')
.pipe(
new PNG({
filterType: 4,
}),
)
.on('parsed', function () {
for (var y = 0; y < this.height; y++) {
for (var x = 0; x < this.width; x++) {
var idx = (this.width * y + x) << 2;
// invert color
this.data[idx] = 255 - this.data[idx];
this.data[idx + 1] = 255 - this.data[idx + 1];
this.data[idx + 2] = 255 - this.data[idx + 2];
// and reduce opacity
this.data[idx + 3] = this.data[idx + 3] >> 1;
}
}
this.pack().pipe(fs.createWriteStream('out.png'));
});
For more examples see examples
folder.
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.
PNG
is readable and writable Stream
.
width
- use this withheight
if you want to create png from scratchheight
- as abovecheckCRC
- whether parser should be strict about checksums in source stream (default:true
)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)deflateLevel
- compression level for deflate (default: 9)deflateStrategy
- compression strategy for deflate (default: 3)deflateFactory
- deflate stream factory (default:zlib.createDeflate
)filterType
- png filtering method for scanlines (default: -1 => auto, accepts array of numbers 0-4)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.inputColorType
- the input colorType - see constants. Default is 6 (RGBA)bitDepth
- the bitDepth of the output, 8 or 16 bits. Input data is expected to have this bit depth. 16 bit data is expected in the system endianness (Default: 8)inputHasAlpha
- whether the input bitmap has 4 bytes per pixel (rgb and alpha) or 3 (rgb - no alpha).bgColor
- an object containing red, green, and blue values between 0 and 255 that is used when packing a PNG if alpha is not to be included (default: 255,255,255)skipRescale
- set to true if you want to skip the rescaling to 8-bit bitmap. This is good if you wish to retain a 16-bit bitmap datastructure.initGrayscaleData
- if you want to initialize the grayscale conversion of the RGBA data for thegrayscaleData
call †.initPropData
- boolean or an object with the arguments toinitPropData
for initializing thepropData
†.
† These functions are useful if you wish to do repeated manipulations to the image and as image manipulation is time consuming it is beneficial to initiate the data from start.
function(metadata) { }
Image's header has been parsed, metadata contains this information:
width
image size in pixelsheight
image size in pixelspalette
image is palettedcolor
image is not grayscalealpha
image contains alpha channelinterlace
image is interlaced
function(data) { }
Input image has been completely parsed, data
is complete and ready for modification.
function(error) { }
Parses PNG file data. Can be String
or Buffer
. Alternatively you can stream data to instance of PNG.
Optional callback
is once called on error
or parsed
. The callback gets
two arguments (err, data)
.
Returns this
for method chaining.
new PNG({ filterType: 4 }).parse(imageData, function (error, data) {
console.log(error, data);
});
Starts converting data to PNG file Stream.
Returns this
for method chaining.
Helper for image manipulation, copies a rectangle of pixels from current (i.e. the source) image
(srcX
, srcY
, width
, height
) to dst
image (at deltaX
, deltaY
).
Returns this
for method chaining.
For example, the following code copies the top-left 100x50 px of in.png
into dst and writes it to out.png
:
const dst = new PNG({ width: 100, height: 50 });
fs.createReadStream('in.png')
.pipe(new PNG())
.on('parsed', function () {
this.bitblt({
dst,
srcX: 0,
srcY: 0,
width: 100,
height: 150,
deltaX: 0,
deltaY: 0,
});
dst.pack().pipe(fs.createWriteStream('out.png'));
});
Not that the package exports bitblt
that takes the additionalargument src
;
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.
In tests against PNG suite it compared 100% with chrome on all 8 bit and below images. On IE there were some differences.
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.
fs.createReadStream('in.png')
.pipe(new PNG())
.on('parsed', function () {
this.adjustGamma();
this.pack().pipe(fs.createWriteStream('out.png'));
});
Width of image in pixels
Height of image in pixels
Object with height and width
Buffer of image pixel data. Every pixel consists 4 bytes: R, G, B, A (opacity).
Gamma of image (0 if not specified)
When using libraries suchs as Redux it is "highly recommended that you only put plain serializable objects, arrays, and primitives into your store". For this purpose PNGJS has implemented the serialize()
and static deserialize()
methods.
import PNG from 'pngjs3';
myPNG = new PNG();
...
const data2store = myPNG.serialize();
...
const myRecreatedObject = PNG.deserialize(data2store);
// Note that:
console.log(myRecreatedObject !== myPNG, 'A new object has been created');
console.log(myRecreatedObject.storage === myPNG.storage, 'But the storage (i.e. data) is the same');
The storage in the PNG-object is immutable through immer
. This means that any changes to the storage will propagate from subitem to the top item. This allows for efficient comparison stora === prevStore
.
When removing the alpha channel from an image, there needs to be a background color to correctly convert each pixel's transparency to the appropriate RGB value. By default, pngjs will flatten the image against a white background. You can override this in the options:
import fs from 'fs';
import PNG from 'pngjs3';
fs.createReadStream('in.png')
.pipe(
new PNG({
colorType: 2,
bgColor: {
red: 0,
green: 255,
blue: 0,
},
}),
)
.on('parsed', function () {
this.pack().pipe(fs.createWriteStream('out.png'));
});
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.
import { sync as PNGSync } from 'pngjs3';
const data = fs.readFileSync('in.png');
const png = PNGSync.read(data);
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.
import { sync as PNGSync } from 'pngjs3';
const data = fs.readFileSync('in.png');
const png = PNGSync.read(data);
const options = { colorType: 6 };
const buffer = PNGSync.write(png, options);
fs.writeFileSync('out.png', buffer);
Adjusts the gamma of a sync image. See the async adjustGamma.
import { adjustGamma } from 'pngjs3';
const data = fs.readFileSync('in.png');
const png = PNGSync.read(data);
adjustGamma(png);
- BREAKING - Sync version now throws if there is unexpected content at the end of the stream.
- BREAKING - Drop support for node 10 (Though nothing incompatible in this release yet)
- Update package dependencies
- Fixed rollup issues
- Removed circular dependency
- Update package dependencies
- Added changes implemented in original pngjs
- Update package dependencies
- Converted Buffer() to Buffer.from & Buffer.alloc
- Drop support for Node v8
- Update package dependencies
- Implemented immutable store (setters and getters should allow for the same functionality as before) - issue #49
- There is a
shape
attribute with thewidth
and theheight
- For storage you can now use
serialize()
andstatic deserialize()
- Added with commits from original fork (https://github.com/lukeapage/pngjs) implemented fixes and improvements should now match
- Updated packages
- Homepage url + package updates
- Updated packages
- Updated packages
- BREAKING: The sync is exported as sync and no longer a static member of the PNG-class
- Default export is now the PNG class
- Separate export for
adjustGamma
,bitblt
andsync
- The
bitblt
now expects an object as argument due to too many arguments - Updated the README to match the new structure
- Change to browserify-zlib (causes one async test case to fail :-()
- Change to rollup - now includes es6 module, umd and cjs
- Package updates
- Fixes to buggy flow interface
- Added propData2ImageClamped for copying propData into Uint8ClampedArray
- Fixed bug in propData
- Changed min/max value search to for loop with break
- Fixed bug in grayscaleData for rgb
- Fixed Flow typings with all the sub-elements
- Fork to pngjs3
- Added browserify for browser loading
- Added propData and grayscaleData
- Added Flow typings
- Bugfixes and removal of es6
- Bugfixes and removal of es6
- Add writing 16 bit channels and support for grayscale input
- Support for encoding 8-bit grayscale images
- Support for pngs with zlib chunks that are malformed after valid data
- Fix single pixel pngs
- Drop support for node below v4 and iojs. Pin to 2.3.0 to use with old, unsupported or patched node versions.
- Support for sync in node 0.10
- Add sync write api
- Fix newfile example
- Correct comparison table
- rename package to pngjs
- added 'bgColor' option
- fixes to readme
- breaking change - bitblt on the png prototype now doesn't take a unused, unnecessary src first argument
- support passing colorType to write PNG's and writing bitmaps without alpha information
- support passing a deflate factory for controlled compression
- Expose all PNG creation info
- Fix non square interlaced files
- More tests
- source linted
- maintainability refactorings
- async API - exceptions in reading now emit warnings
- documentation improvement - sync api now documented, adjustGamma documented
- breaking change - gamma chunk is now written. previously a read then write would destroy gamma information, now it is persisted.
- Error handling fixes
- ignore files for smaller npm footprint
- Bugfixes to interlacing, support for transparent colours
- Initial release, see pngjs for older changelog.
(The MIT License)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.