Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
PNG encoder/decoder in pure JS, supporting any bit size & interlace, async & sync with full test suite.
The pngjs npm package is a pure JavaScript implementation for PNG encoding and decoding in Node.js. It allows for reading and writing PNG images in a non-blocking and streaming way, which is useful for applications that need to handle image data directly.
Reading PNG files
This code demonstrates how to read a PNG file using pngjs. It creates a read stream from a file, pipes it through the PNG decoder, and logs the image's width and height once it's parsed.
const fs = require('fs');
const PNG = require('pngjs').PNG;
fs.createReadStream('input.png')
.pipe(new PNG())
.on('parsed', function() {
console.log('Image width:', this.width, 'Image height:', this.height);
});
Writing PNG files
This code snippet shows how to create a new PNG image with a specific width and height, fill it with white color, and then write it to a file. It demonstrates the package's ability to write PNG files.
const fs = require('fs');
const PNG = require('pngjs').PNG;
const png = new PNG({ width: 10, height: 10, filterType: -1 });
for (let y = 0; y < png.height; y++) {
for (let x = 0; x < png.width; x++) {
let idx = (png.width * y + x) << 2;
png.data[idx] = 255; // red
png.data[idx + 1] = 255; // green
png.data[idx + 2] = 255; // blue
png.data[idx + 3] = 255; // alpha (opacity)
}
}
png.pack().pipe(fs.createWriteStream('output.png'));
Sharp is a high-performance Node.js image processing library. It allows for converting large images in common formats to smaller, web-friendly JPEG, PNG, WebP, and AVIF images of varying dimensions. Compared to pngjs, sharp supports a wider range of image formats and provides more comprehensive image processing capabilities, but it relies on native dependencies.
Jimp is an image processing library for Node.js, written entirely in JavaScript, with zero native dependencies. It can perform a variety of operations such as resize, crop, rotate, and color manipulation. While Jimp supports PNG among other formats, it offers broader functionality beyond just PNG encoding and decoding, making it more versatile than pngjs for general image processing tasks.
Simple PNG encoder/decoder for Node.js with no dependencies.
Based on the original pngjs with the follow enhancements.
tTRNS
transparent coloursKnown lack of support for:
Name | Forked From | Sync | Async | 16 Bit | 1/2/4 Bit | Interlace | Gamma | Encodes | Tested |
---|---|---|---|---|---|---|---|---|---|
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:
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.
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.
$ npm install pngjs --save
The package has been build with a Browserify version (npm run browserify
) and you can use the browser version by including in your code:
import { PNG } from 'pngjs/browser';
var fs = require('fs'),
PNG = require('pngjs').PNG;
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 with height
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)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 interlacedfunction(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 (sx
, sy
, w
, h
) to dst
image (at dx
, dy
).
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
:
var dst = new PNG({width: 100, height: 50});
fs.createReadStream('in.png')
.pipe(new PNG())
.on('parsed', function() {
this.bitblt(dst, 0, 0, 100, 50, 0, 0);
dst.pack().pipe(fs.createWriteStream('out.png'));
});
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
Buffer of image pixel data. Every pixel consists 4 bytes: R, G, B, A (opacity).
Gamma of image (0 if not specified)
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:
var fs = require('fs'),
PNG = require('pngjs').PNG;
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.
var data = fs.readFileSync('in.png');
var png = PNG.sync.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.
var data = fs.readFileSync('in.png');
var png = PNG.sync.read(data);
var options = { colorType: 6 };
var buffer = PNG.sync.write(png, options);
fs.writeFileSync('out.png', buffer);
Adjusts the gamma of a sync image. See the async adjustGamma.
var data = fs.readFileSync('in.png');
var png = PNG.sync.read(data);
PNG.adjustGamma(png);
(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.
4.0.0 - 09/04/2020
FAQs
PNG encoder/decoder in pure JS, supporting any bit size & interlace, async & sync with full test suite.
The npm package pngjs receives a total of 2,988,349 weekly downloads. As such, pngjs popularity was classified as popular.
We found that pngjs demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.