Socket
Socket
Sign inDemoInstall

pngjs

Package Overview
Dependencies
Maintainers
1
Versions
24
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

pngjs - npm Package Compare versions

Comparing version 0.4.0 to 2.0.0

.eslintrc

251

lib/chunkstream.js

@@ -1,39 +0,19 @@

// Copyright (c) 2012 Kuba Niegowski
//
// 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.
'use strict';
var util = require('util'),
Stream = require('stream');
var util = require('util');
var Stream = require('stream');
var ChunkStream = module.exports = function() {
Stream.call(this);
Stream.call(this);
this._buffers = [];
this._buffered = 0;
this._buffers = [];
this._buffered = 0;
this._reads = [];
this._paused = false;
this._reads = [];
this._paused = false;
this._encoding = 'utf8';
this.writable = true;
this._encoding = 'utf8';
this.writable = true;
};

@@ -45,8 +25,9 @@ util.inherits(ChunkStream, Stream);

this._reads.push({
length: Math.abs(length), // if length < 0 then at most this length
allowLess: length < 0,
func: callback
});
this._reads.push({
length: Math.abs(length), // if length < 0 then at most this length
allowLess: length < 0,
func: callback
});
process.nextTick(function() {
this._process();

@@ -56,6 +37,7 @@

if (this._paused && this._reads.length > 0) {
this._paused = false;
this._paused = false;
this.emit('drain');
this.emit('drain');
}
}.bind(this));
};

@@ -65,20 +47,26 @@

if (!this.writable) {
this.emit('error', new Error('Stream not writable'));
return false;
}
if (!this.writable) {
this.emit('error', new Error('Stream not writable'));
return false;
}
if (!Buffer.isBuffer(data))
data = new Buffer(data, encoding || this._encoding);
var dataBuffer;
if (Buffer.isBuffer(data)) {
dataBuffer = data;
}
else {
dataBuffer = new Buffer(data, encoding || this._encoding);
}
this._buffers.push(data);
this._buffered += data.length;
this._buffers.push(dataBuffer);
this._buffered += dataBuffer.length;
this._process();
this._process();
// ok if there are no more read requests
if (this._reads && this._reads.length == 0)
this._paused = true;
// ok if there are no more read requests
if (this._reads && this._reads.length === 0) {
this._paused = true;
}
return this.writable && !this._paused;
return this.writable && !this._paused;
};

@@ -88,16 +76,21 @@

if (data) this.write(data, encoding);
if (data) {
this.write(data, encoding);
}
this.writable = false;
this.writable = false;
// already destroyed
if (!this._buffers) return;
// already destroyed
if (!this._buffers) {
return;
}
// enqueue or handle end
if (this._buffers.length == 0) {
this._end();
} else {
this._buffers.push(null);
this._process();
}
// enqueue or handle end
if (this._buffers.length === 0) {
this._end();
}
else {
this._buffers.push(null);
this._process();
}
};

@@ -109,9 +102,9 @@

if (this._reads.length > 0) {
this.emit('error',
new Error('There are some read requests waitng on finished stream')
);
}
if (this._reads.length > 0) {
this.emit('error',
new Error('There are some read requests waitng on finished stream')
);
}
this.destroy();
this.destroy();
};

@@ -121,84 +114,102 @@

if (!this._buffers) return;
if (!this._buffers) {
return;
}
this.writable = false;
this._reads = null;
this._buffers = null;
this.writable = false;
this._reads = null;
this._buffers = null;
this.emit('close');
this.emit('close');
};
ChunkStream.prototype._process = function() {
ChunkStream.prototype._processReadAllowingLess = function(read) {
// ok there is any data so that we can satisfy this request
this._reads.shift(); // == read
// as long as there is any data and read requests
while (this._buffered > 0 && this._reads && this._reads.length > 0) {
// first we need to peek into first buffer
var smallerBuf = this._buffers[0];
var read = this._reads[0];
// ok there is more data than we need
if (smallerBuf.length > read.length) {
// read any data (but no more than length)
if (read.allowLess) {
this._buffered -= read.length;
this._buffers[0] = smallerBuf.slice(read.length);
// ok there is any data so that we can satisfy this request
this._reads.shift(); // == read
read.func.call(this, smallerBuf.slice(0, read.length));
// first we need to peek into first buffer
var buf = this._buffers[0];
}
else {
// ok this is less than maximum length so use it all
this._buffered -= smallerBuf.length;
this._buffers.shift(); // == smallerBuf
// ok there is more data than we need
if (buf.length > read.length) {
read.func.call(this, smallerBuf);
}
};
this._buffered -= read.length;
this._buffers[0] = buf.slice(read.length);
ChunkStream.prototype._processRead = function(read) {
this._reads.shift(); // == read
read.func.call(this, buf.slice(0, read.length));
var pos = 0;
var count = 0;
var data = new Buffer(read.length);
} else {
// ok this is less than maximum length so use it all
this._buffered -= buf.length;
this._buffers.shift(); // == buf
// create buffer for all data
while (pos < read.length) {
read.func.call(this, buf);
}
var buf = this._buffers[count++];
var len = Math.min(buf.length, read.length - pos);
} else if (this._buffered >= read.length) {
// ok we can meet some expectations
buf.copy(data, pos, 0, len);
pos += len;
this._reads.shift(); // == read
// last buffer wasn't used all so just slice it and leave
if (len !== buf.length) {
this._buffers[--count] = buf.slice(len);
}
}
var pos = 0,
count = 0,
data = new Buffer(read.length);
// remove all used buffers
if (count > 0) {
this._buffers.splice(0, count);
}
// create buffer for all data
while (pos < read.length) {
this._buffered -= read.length;
var buf = this._buffers[count++],
len = Math.min(buf.length, read.length - pos);
read.func.call(this, data);
};
buf.copy(data, pos, 0, len);
pos += len;
ChunkStream.prototype._process = function() {
// last buffer wasn't used all so just slice it and leave
if (len != buf.length)
this._buffers[--count] = buf.slice(len);
}
try {
// as long as there is any data and read requests
while (this._buffered > 0 && this._reads && this._reads.length > 0) {
// remove all used buffers
if (count > 0)
this._buffers.splice(0, count);
var read = this._reads[0];
this._buffered -= read.length;
// read any data (but no more than length)
if (read.allowLess) {
this._processReadAllowingLess(read);
read.func.call(this, data);
}
else if (this._buffered >= read.length) {
// ok we can meet some expectations
} else {
// not enought data to satisfy first request in queue
// so we need to wait for more
break;
}
this._processRead(read);
}
else {
// not enought data to satisfy first request in queue
// so we need to wait for more
break;
}
}
if (this._buffers && this._buffers.length > 0 && this._buffers[0] == null) {
this._end();
if (this._buffers && this._buffers.length > 0 && this._buffers[0] === null) {
this._end();
}
}
catch (ex) {
this.emit('error', ex);
}
};

@@ -1,21 +0,1 @@

// Copyright (c) 2012 Kuba Niegowski
//
// 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.
'use strict';

@@ -26,14 +6,30 @@

PNG_SIGNATURE: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a],
PNG_SIGNATURE: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a],
TYPE_IHDR: 0x49484452,
TYPE_IEND: 0x49454e44,
TYPE_IDAT: 0x49444154,
TYPE_PLTE: 0x504c5445,
TYPE_tRNS: 0x74524e53,
TYPE_gAMA: 0x67414d41,
TYPE_IHDR: 0x49484452,
TYPE_IEND: 0x49454e44,
TYPE_IDAT: 0x49444154,
TYPE_PLTE: 0x504c5445,
TYPE_tRNS: 0x74524e53, // eslint-disable-line camelcase
TYPE_gAMA: 0x67414d41, // eslint-disable-line camelcase
COLOR_PALETTE: 1,
COLOR_COLOR: 2,
COLOR_ALPHA: 4
// color-type bits
COLORTYPE_GRAYSCALE: 0,
COLORTYPE_PALETTE: 1,
COLORTYPE_COLOR: 2,
COLORTYPE_ALPHA: 4, // e.g. grayscale and alpha
// color-type combinations
COLORTYPE_PALETTE_COLOR: 3,
COLORTYPE_COLOR_ALPHA: 6,
COLORTYPE_TO_BPP_MAP: {
0: 1,
2: 3,
3: 1,
4: 2,
6: 4
},
GAMMA_DIVISION: 100000
};

@@ -1,79 +0,44 @@

// Copyright (c) 2012 Kuba Niegowski
//
// 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.
'use strict';
var util = require('util'),
Stream = require('stream');
var crcTable = [];
(function() {
for (var i = 0; i < 256; i++) {
var currentCrc = i;
for (var j = 0; j < 8; j++) {
if (currentCrc & 1) {
currentCrc = 0xedb88320 ^ (currentCrc >>> 1);
}
else {
currentCrc = currentCrc >>> 1;
}
}
crcTable[i] = currentCrc;
}
}());
var CrcStream = module.exports = function() {
Stream.call(this);
this._crc = -1;
this.writable = true;
var CrcCalculator = module.exports = function() {
this._crc = -1;
};
util.inherits(CrcStream, Stream);
CrcCalculator.prototype.write = function(data) {
CrcStream.prototype.write = function(data) {
for (var i = 0; i < data.length; i++) {
this._crc = crcTable[(this._crc ^ data[i]) & 0xff] ^ (this._crc >>> 8);
}
return true;
for (var i = 0; i < data.length; i++) {
this._crc = crcTable[(this._crc ^ data[i]) & 0xff] ^ (this._crc >>> 8);
}
return true;
};
CrcStream.prototype.end = function(data) {
if (data) this.write(data);
this.emit('crc', this.crc32());
CrcCalculator.prototype.crc32 = function() {
return this._crc ^ -1;
};
CrcStream.prototype.crc32 = function() {
return this._crc ^ -1;
};
CrcCalculator.crc32 = function(buf) {
CrcStream.crc32 = function(buf) {
var crc = -1;
for (var i = 0; i < buf.length; i++) {
crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
}
return crc ^ -1;
var crc = -1;
for (var i = 0; i < buf.length; i++) {
crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
}
return crc ^ -1;
};
var crcTable = [];
for (var i = 0; i < 256; i++) {
var c = i;
for (var j = 0; j < 8; j++) {
if (c & 1) {
c = 0xedb88320 ^ (c >>> 1);
} else {
c = c >>> 1;
}
}
crcTable[i] = c;
}

@@ -1,42 +0,32 @@

// Copyright (c) 2012 Kuba Niegowski
//
// 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.
'use strict';
var util = require('util');
var Stream = require('stream');
var zlib = require('zlib');
var filter = require('./filter-pack');
var CrcStream = require('./crc');
var constants = require('./constants');
var bitPacker = require('./bitpacker');
var util = require('util'),
Stream = require('stream'),
zlib = require('zlib'),
Filter = require('./filter'),
CrcStream = require('./crc'),
constants = require('./constants');
var Packer = module.exports = function(options) {
Stream.call(this);
this._options = options;
var Packer = module.exports = function(options) {
Stream.call(this);
options.deflateChunkSize = options.deflateChunkSize || 32 * 1024;
options.deflateLevel = options.deflateLevel != null ? options.deflateLevel : 9;
options.deflateStrategy = options.deflateStrategy != null ? options.deflateStrategy : 3;
options.inputHasAlpha = options.inputHasAlpha != null ? options.inputHasAlpha : true;
options.deflateFactory = options.deflateFactory || zlib.createDeflate;
options.bitDepth = options.bitDepth || 8;
options.colorType = (typeof options.colorType === 'number') ? options.colorType : constants.COLORTYPE_COLOR_ALPHA;
this._options = options;
if (options.colorType !== constants.COLORTYPE_COLOR && options.colorType !== constants.COLORTYPE_COLOR_ALPHA) {
throw new Error('option color type:' + options.colorType + ' is not supported at present');
}
if (options.bitDepth !== 8) {
throw new Error('option bit depth:' + options.bitDepth + ' is not supported at present');
}
options.deflateChunkSize = options.deflateChunkSize || 32 * 1024;
options.deflateLevel = options.deflateLevel || 9;
options.deflateStrategy = options.deflateStrategy || 3;
this.readable = true;
this.readable = true;
};

@@ -46,30 +36,36 @@ util.inherits(Packer, Stream);

Packer.prototype.pack = function(data, width, height) {
Packer.prototype.pack = function(data, width, height, gamma) {
// Signature
this.emit('data', new Buffer(constants.PNG_SIGNATURE));
this.emit('data', this._packIHDR(width, height, this._options.bitDepth, this._options.colorType));
// Signature
this.emit('data', new Buffer(constants.PNG_SIGNATURE));
this.emit('data', this._packIHDR(width, height));
if (gamma) {
this.emit('data', this._packGAMA(gamma));
}
// filter pixel data
var filter = new Filter(width, height, 4, data, this._options);
var data = filter.filter();
// convert to correct format for filtering (e.g. right bpp and bit depth)
var packedData = bitPacker(data, width, height, this._options);
// compress it
var deflate = zlib.createDeflate({
chunkSize: this._options.deflateChunkSize,
level: this._options.deflateLevel,
strategy: this._options.deflateStrategy
});
deflate.on('error', this.emit.bind(this, 'error'));
// filter pixel data
var bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];
var filteredData = filter(packedData, width, height, this._options, bpp);
deflate.on('data', function(data) {
this.emit('data', this._packIDAT(data));
}.bind(this));
// compress it
var deflate = this._options.deflateFactory({
chunkSize: this._options.deflateChunkSize,
level: this._options.deflateLevel,
strategy: this._options.deflateStrategy
});
deflate.on('error', this.emit.bind(this, 'error'));
deflate.on('end', function() {
this.emit('data', this._packIEND());
this.emit('end');
}.bind(this));
deflate.on('data', function(compressedData) {
this.emit('data', this._packIDAT(compressedData));
}.bind(this));
deflate.end(data);
deflate.on('end', function() {
this.emit('data', this._packIEND());
this.emit('end');
}.bind(this));
deflate.end(filteredData);
};

@@ -79,34 +75,42 @@

var len = (data ? data.length : 0),
buf = new Buffer(len + 12);
var len = (data ? data.length : 0);
var buf = new Buffer(len + 12);
buf.writeUInt32BE(len, 0);
buf.writeUInt32BE(type, 4);
buf.writeUInt32BE(len, 0);
buf.writeUInt32BE(type, 4);
if (data) data.copy(buf, 8);
if (data) {
data.copy(buf, 8);
}
buf.writeInt32BE(CrcStream.crc32(buf.slice(4, buf.length - 4)), buf.length - 4);
return buf;
buf.writeInt32BE(CrcStream.crc32(buf.slice(4, buf.length - 4)), buf.length - 4);
return buf;
};
Packer.prototype._packIHDR = function(width, height) {
Packer.prototype._packGAMA = function(gamma) {
var buf = new Buffer(4);
buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0);
return this._packChunk(constants.TYPE_gAMA, buf);
};
var buf = new Buffer(13);
buf.writeUInt32BE(width, 0);
buf.writeUInt32BE(height, 4);
buf[8] = 8;
buf[9] = 6; // colorType
buf[10] = 0; // compression
buf[11] = 0; // filter
buf[12] = 0; // interlace
Packer.prototype._packIHDR = function(width, height, bitDepth, colorType) {
return this._packChunk(constants.TYPE_IHDR, buf);
var buf = new Buffer(13);
buf.writeUInt32BE(width, 0);
buf.writeUInt32BE(height, 4);
buf[8] = bitDepth; // Bit depth
buf[9] = colorType; // colorType
buf[10] = 0; // compression
buf[11] = 0; // filter
buf[12] = 0; // interlace
return this._packChunk(constants.TYPE_IHDR, buf);
};
Packer.prototype._packIDAT = function(data) {
return this._packChunk(constants.TYPE_IDAT, data);
return this._packChunk(constants.TYPE_IDAT, data);
};
Packer.prototype._packIEND = function() {
return this._packChunk(constants.TYPE_IEND, null);
return this._packChunk(constants.TYPE_IEND, null);
};

@@ -1,92 +0,56 @@

// Copyright (c) 2012 Kuba Niegowski
//
// 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.
'use strict';
var constants = require('./constants');
var CrcCalculator = require('./crc');
var util = require('util'),
zlib = require('zlib'),
CrcStream = require('./crc'),
ChunkStream = require('./chunkstream'),
constants = require('./constants'),
Filter = require('./filter');
var Parser = module.exports = function(options, dependencies) {
var Parser = module.exports = function(options) {
ChunkStream.call(this);
this._options = options;
options.checkCRC = options.checkCRC !== false;
this._options = options;
options.checkCRC = options.checkCRC !== false;
this._hasIHDR = false;
this._hasIEND = false;
this._hasIHDR = false;
this._hasIEND = false;
// input flags/metadata
this._palette = [];
this._colorType = 0;
this._inflate = null;
this._filter = null;
this._crc = null;
this._chunks = {};
this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this);
this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this);
this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this);
this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this);
this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this);
this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this);
// input flags/metadata
this._palette = [];
this._colorType = 0;
this._chunks = {};
this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this);
this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this);
this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this);
this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this);
this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this);
this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this);
this.writable = true;
this.on('error', this._handleError.bind(this));
this._handleSignature();
this.read = dependencies.read;
this.error = dependencies.error;
this.metadata = dependencies.metadata;
this.gamma = dependencies.gamma;
this.transColor = dependencies.transColor;
this.palette = dependencies.palette;
this.parsed = dependencies.parsed;
this.inflateData = dependencies.inflateData;
this.inflateData = dependencies.inflateData;
this.finished = dependencies.finished;
};
util.inherits(Parser, ChunkStream);
Parser.prototype._handleError = function() {
this.writable = false;
this.destroy();
if (this._inflate)
this._inflate.destroy();
Parser.prototype.start = function() {
this.read(constants.PNG_SIGNATURE.length,
this._parseSignature.bind(this)
);
};
Parser.prototype._handleSignature = function() {
this.read(constants.PNG_SIGNATURE.length,
this._parseSignature.bind(this)
);
};
Parser.prototype._parseSignature = function(data) {
var signature = constants.PNG_SIGNATURE;
var signature = constants.PNG_SIGNATURE;
for (var i = 0; i < signature.length; i++) {
if (data[i] != signature[i]) {
this.emit('error', new Error('Invalid file signature'));
return;
}
for (var i = 0; i < signature.length; i++) {
if (data[i] !== signature[i]) {
this.error(new Error('Invalid file signature'));
return;
}
this.read(8, this._parseChunkBegin.bind(this));
}
this.read(8, this._parseChunkBegin.bind(this));
};

@@ -96,43 +60,45 @@

// chunk content length
var length = data.readUInt32BE(0);
// chunk content length
var length = data.readUInt32BE(0);
// chunk type
var type = data.readUInt32BE(4),
name = '';
for (var i = 4; i < 8; i++)
name += String.fromCharCode(data[i]);
// chunk type
var type = data.readUInt32BE(4);
var name = '';
for (var i = 4; i < 8; i++) {
name += String.fromCharCode(data[i]);
}
// console.log('chunk ', name, length);
//console.log('chunk ', name, length);
// chunk flags
var ancillary = !!(data[4] & 0x20), // or critical
priv = !!(data[5] & 0x20), // or public
safeToCopy = !!(data[7] & 0x20); // or unsafe
// chunk flags
var ancillary = Boolean(data[4] & 0x20); // or critical
// priv = Boolean(data[5] & 0x20), // or public
// safeToCopy = Boolean(data[7] & 0x20); // or unsafe
if (!this._hasIHDR && type != constants.TYPE_IHDR) {
this.emit('error', new Error('Expected IHDR on beggining'));
return;
}
if (!this._hasIHDR && type !== constants.TYPE_IHDR) {
this.error(new Error('Expected IHDR on beggining'));
return;
}
this._crc = new CrcStream();
this._crc.write(new Buffer(name));
this._crc = new CrcCalculator();
this._crc.write(new Buffer(name));
if (this._chunks[type]) {
return this._chunks[type](length);
if (this._chunks[type]) {
return this._chunks[type](length);
}
} else if (!ancillary) {
this.emit('error', new Error('Unsupported critical chunk type ' + name));
return;
} else {
this.read(length + 4, this._skipChunk.bind(this));
}
if (!ancillary) {
this.error(new Error('Unsupported critical chunk type ' + name));
return;
}
this.read(length + 4, this._skipChunk.bind(this));
};
Parser.prototype._skipChunk = function(data) {
this.read(8, this._parseChunkBegin.bind(this));
Parser.prototype._skipChunk = function(/*data*/) {
this.read(8, this._parseChunkBegin.bind(this));
};
Parser.prototype._handleChunkEnd = function() {
this.read(4, this._parseChunkEnd.bind(this));
this.read(4, this._parseChunkEnd.bind(this));
};

@@ -142,83 +108,76 @@

var fileCrc = data.readInt32BE(0),
calcCrc = this._crc.crc32();
var fileCrc = data.readInt32BE(0);
var calcCrc = this._crc.crc32();
// check CRC
if (this._options.checkCRC && calcCrc != fileCrc) {
this.emit('error', new Error('Crc error'));
return;
}
// check CRC
if (this._options.checkCRC && calcCrc !== fileCrc) {
this.error(new Error('Crc error - ' + fileCrc + ' - ' + calcCrc));
return;
}
if (this._hasIEND) {
this.destroySoon();
} else {
this.read(8, this._parseChunkBegin.bind(this));
}
if (!this._hasIEND) {
this.read(8, this._parseChunkBegin.bind(this));
}
};
Parser.prototype._handleIHDR = function(length) {
this.read(length, this._parseIHDR.bind(this));
this.read(length, this._parseIHDR.bind(this));
};
Parser.prototype._parseIHDR = function(data) {
this._crc.write(data);
this._crc.write(data);
var width = data.readUInt32BE(0),
height = data.readUInt32BE(4),
depth = data[8],
colorType = data[9], // bits: 1 palette, 2 color, 4 alpha
compr = data[10],
filter = data[11],
interlace = data[12];
var width = data.readUInt32BE(0);
var height = data.readUInt32BE(4);
var depth = data[8];
var colorType = data[9]; // bits: 1 palette, 2 color, 4 alpha
var compr = data[10];
var filter = data[11];
var interlace = data[12];
// console.log(' width', width, 'height', height,
// 'depth', depth, 'colorType', colorType,
// 'compr', compr, 'filter', filter, 'interlace', interlace
// );
// console.log(' width', width, 'height', height,
// 'depth', depth, 'colorType', colorType,
// 'compr', compr, 'filter', filter, 'interlace', interlace
// );
if (depth != 8) {
this.emit('error', new Error('Unsupported bit depth ' + depth));
return;
}
if (!(colorType in colorTypeToBppMap)) {
this.emit('error', new Error('Unsupported color type'));
return;
}
if (compr != 0) {
this.emit('error', new Error('Unsupported compression method'));
return;
}
if (filter != 0) {
this.emit('error', new Error('Unsupported filter method'));
return;
}
if (interlace != 0) {
this.emit('error', new Error('Unsupported interlace method'));
return;
}
if (depth !== 8 && depth !== 4 && depth !== 2 && depth !== 1 && depth !== 16) {
this.error(new Error('Unsupported bit depth ' + depth));
return;
}
if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) {
this.error(new Error('Unsupported color type'));
return;
}
if (compr !== 0) {
this.error(new Error('Unsupported compression method'));
return;
}
if (filter !== 0) {
this.error(new Error('Unsupported filter method'));
return;
}
if (interlace !== 0 && interlace !== 1) {
this.error(new Error('Unsupported interlace method'));
return;
}
this._colorType = colorType;
this._colorType = colorType;
this._data = new Buffer(width * height * 4);
this._filter = new Filter(
width, height,
colorTypeToBppMap[this._colorType],
this._data,
this._options
);
var bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType];
this._hasIHDR = true;
this._hasIHDR = true;
this.emit('metadata', {
width: width,
height: height,
palette: !!(colorType & constants.COLOR_PALETTE),
color: !!(colorType & constants.COLOR_COLOR),
alpha: !!(colorType & constants.COLOR_ALPHA),
data: this._data
});
this.metadata({
width: width,
height: height,
depth: depth,
interlace: Boolean(interlace),
palette: Boolean(colorType & constants.COLORTYPE_PALETTE),
color: Boolean(colorType & constants.COLORTYPE_COLOR),
alpha: Boolean(colorType & constants.COLORTYPE_ALPHA),
bpp: bpp,
colorType: colorType
});
this._handleChunkEnd();
this._handleChunkEnd();
};

@@ -228,135 +187,107 @@

Parser.prototype._handlePLTE = function(length) {
this.read(length, this._parsePLTE.bind(this));
this.read(length, this._parsePLTE.bind(this));
};
Parser.prototype._parsePLTE = function(data) {
this._crc.write(data);
this._crc.write(data);
var entries = Math.floor(data.length / 3);
// console.log('Palette:', entries);
var entries = Math.floor(data.length / 3);
// console.log('Palette:', entries);
for (var i = 0; i < entries; i++) {
this._palette.push([
data.readUInt8(i * 3),
data.readUInt8(i * 3 + 1),
data.readUInt8(i * 3 + 2 ),
0xff
]);
}
for (var i = 0; i < entries; i++) {
this._palette.push([
data[i * 3],
data[i * 3 + 1],
data[i * 3 + 2],
0xff
]);
}
this._handleChunkEnd();
this.palette(this._palette);
this._handleChunkEnd();
};
Parser.prototype._handleTRNS = function(length) {
this.read(length, this._parseTRNS.bind(this));
this.read(length, this._parseTRNS.bind(this));
};
Parser.prototype._parseTRNS = function(data) {
this._crc.write(data);
this._crc.write(data);
// palette
if (this._colorType == 3) {
if (this._palette.length == 0) {
this.emit('error', new Error('Transparency chunk must be after palette'));
return;
}
if (data.length > this._palette.length) {
this.emit('error', new Error('More transparent colors than palette size'));
return;
}
for (var i = 0; i < this._palette.length; i++) {
this._palette[i][3] = i < data.length ? data.readUInt8(i) : 0xff;
}
// palette
if (this._colorType === constants.COLORTYPE_PALETTE_COLOR) {
if (this._palette.length === 0) {
this.error(new Error('Transparency chunk must be after palette'));
return;
}
if (data.length > this._palette.length) {
this.error(new Error('More transparent colors than palette size'));
return;
}
for (var i = 0; i < data.length; i++) {
this._palette[i][3] = data[i];
}
this.palette(this._palette);
}
// for colorType 0 (grayscale) and 2 (rgb)
// there might be one gray/color defined as transparent
// for colorType 0 (grayscale) and 2 (rgb)
// there might be one gray/color defined as transparent
if (this._colorType === constants.COLORTYPE_GRAYSCALE) {
// grey, 2 bytes
this.transColor([data.readUInt16BE(0)]);
}
if (this._colorType === constants.COLORTYPE_COLOR) {
this.transColor([data.readUInt16BE(0), data.readUInt16BE(2), data.readUInt16BE(4)]);
}
this._handleChunkEnd();
this._handleChunkEnd();
};
Parser.prototype._handleGAMA = function(length) {
this.read(length, this._parseGAMA.bind(this));
this.read(length, this._parseGAMA.bind(this));
};
Parser.prototype._parseGAMA = function(data) {
this._crc.write(data);
this.emit('gamma', data.readUInt32BE(0) / 100000);
this._crc.write(data);
this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION);
this._handleChunkEnd();
this._handleChunkEnd();
};
Parser.prototype._handleIDAT = function(length) {
this.read(-length, this._parseIDAT.bind(this, length));
this.read(-length, this._parseIDAT.bind(this, length));
};
Parser.prototype._parseIDAT = function(length, data) {
this._crc.write(data);
this._crc.write(data);
if (this._colorType == 3 && this._palette.length == 0)
throw new Error('Expected palette not found');
if (this._colorType === constants.COLORTYPE_PALETTE_COLOR && this._palette.length === 0) {
throw new Error('Expected palette not found');
}
if (!this._inflate) {
this._inflate = zlib.createInflate();
this.inflateData(data);
var leftOverLength = length - data.length;
this._inflate.on('error', this.emit.bind(this, 'error'));
this._filter.on('complete', this._reverseFiltered.bind(this));
this._inflate.pipe(this._filter);
}
this._inflate.write(data);
length -= data.length;
if (length > 0)
this._handleIDAT(length);
else
this._handleChunkEnd();
if (leftOverLength > 0) {
this._handleIDAT(leftOverLength);
}
else {
this._handleChunkEnd();
}
};
Parser.prototype._handleIEND = function(length) {
this.read(length, this._parseIEND.bind(this));
this.read(length, this._parseIEND.bind(this));
};
Parser.prototype._parseIEND = function(data) {
this._crc.write(data);
this._crc.write(data);
// no more data to inflate
this._inflate.end();
this._hasIEND = true;
this._handleChunkEnd();
this._hasIEND = true;
this._handleChunkEnd();
if (this.finished) {
this.finished();
}
};
var colorTypeToBppMap = {
0: 1,
2: 3,
3: 1,
4: 2,
6: 4
};
Parser.prototype._reverseFiltered = function(data, width, height) {
if (this._colorType == 3) { // paletted
// use values from palette
var pxLineLength = width << 2;
for (var y = 0; y < height; y++) {
var pxRowPos = y * pxLineLength;
for (var x = 0; x < width; x++) {
var pxPos = pxRowPos + (x << 2),
color = this._palette[data[pxPos]];
for (var i = 0; i < 4; i++)
data[pxPos + i] = color[i];
}
}
}
this.emit('parsed', data);
};

@@ -1,72 +0,62 @@

// Copyright (c) 2012 Kuba Niegowski
//
// 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.
'use strict';
var util = require('util');
var Stream = require('stream');
var Parser = require('./parser-async');
var Packer = require('./packer');
var PNGSync = require('./png-sync');
var util = require('util'),
Stream = require('stream'),
Parser = require('./parser'),
Packer = require('./packer');
var PNG = exports.PNG = function(options) {
Stream.call(this);
Stream.call(this);
options = options || {};
options = options || {}; // eslint-disable-line no-param-reassign
this.width = options.width || 0;
this.height = options.height || 0;
this.width = options.width || 0;
this.height = options.height || 0;
this.data = this.width > 0 && this.height > 0
? new Buffer(4 * this.width * this.height) : null;
this.data = this.width > 0 && this.height > 0 ?
new Buffer(4 * this.width * this.height) : null;
this.gamma = 0;
this.readable = this.writable = true;
if (options.fill && this.data) {
this.data.fill(0);
}
this._parser = new Parser(options || {});
this.gamma = 0;
this.readable = this.writable = true;
this._parser.on('error', this.emit.bind(this, 'error'));
this._parser.on('close', this._handleClose.bind(this));
this._parser.on('metadata', this._metadata.bind(this));
this._parser.on('gamma', this._gamma.bind(this));
this._parser.on('parsed', function(data) {
this.data = data;
this.emit('parsed', data);
}.bind(this));
this._parser = new Parser(options);
this._packer = new Packer(options);
this._packer.on('data', this.emit.bind(this, 'data'));
this._packer.on('end', this.emit.bind(this, 'end'));
this._parser.on('close', this._handleClose.bind(this));
this._packer.on('error', this.emit.bind(this, 'error'));
this._parser.on('error', this.emit.bind(this, 'error'));
this._parser.on('close', this._handleClose.bind(this));
this._parser.on('metadata', this._metadata.bind(this));
this._parser.on('gamma', this._gamma.bind(this));
this._parser.on('parsed', function(data) {
this.data = data;
this.emit('parsed', data);
}.bind(this));
this._packer = new Packer(options);
this._packer.on('data', this.emit.bind(this, 'data'));
this._packer.on('end', this.emit.bind(this, 'end'));
this._parser.on('close', this._handleClose.bind(this));
this._packer.on('error', this.emit.bind(this, 'error'));
};
util.inherits(PNG, Stream);
PNG.sync = PNGSync;
PNG.prototype.pack = function() {
process.nextTick(function() {
this._packer.pack(this.data, this.width, this.height);
}.bind(this));
if (!this.data || !this.data.length) {
this.emit('error', 'No data provided');
return this;
}
return this;
process.nextTick(function() {
this._packer.pack(this.data, this.width, this.height, this.gamma);
}.bind(this));
return this;
};

@@ -77,72 +67,98 @@

if (callback) {
var onParsed = null, onError = null;
if (callback) {
var onParsed, onError;
this.once('parsed', onParsed = function(data) {
this.removeListener('error', onError);
onParsed = function(parsedData) {
this.removeListener('error', onError);
this.data = data;
callback(null, this);
this.data = parsedData;
callback(null, this);
}.bind(this);
}.bind(this));
onError = function(err) {
this.removeListener('parsed', onParsed);
this.once('error', onError = function(err) {
this.removeListener('parsed', onParsed);
callback(err, null);
}.bind(this);
callback(err, null);
}.bind(this));
}
this.once('parsed', onParsed);
this.once('error', onError);
}
this.end(data);
return this;
this.end(data);
return this;
};
PNG.prototype.write = function(data) {
this._parser.write(data);
return true;
this._parser.write(data);
return true;
};
PNG.prototype.end = function(data) {
this._parser.end(data);
this._parser.end(data);
};
PNG.prototype._metadata = function(metadata) {
this.width = metadata.width;
this.height = metadata.height;
this.data = metadata.data;
this.width = metadata.width;
this.height = metadata.height;
delete metadata.data;
this.emit('metadata', metadata);
this.emit('metadata', metadata);
};
PNG.prototype._gamma = function(gamma) {
this.gamma = gamma;
this.gamma = gamma;
};
PNG.prototype._handleClose = function() {
if (!this._parser.writable && !this._packer.readable)
this.emit('close');
if (!this._parser.writable && !this._packer.readable) {
this.emit('close');
}
};
PNG.prototype.bitblt = function(dst, sx, sy, w, h, dx, dy) {
PNG.bitblt = function(src, dst, srcX, srcY, width, height, deltaX, deltaY) { // eslint-disable-line max-params
var src = this;
if (srcX > src.width || srcY > src.height || srcX + width > src.width || srcY + height > src.height) {
throw new Error('bitblt reading outside image');
}
if (sx > src.width || sy > src.height
|| sx + w > src.width || sy + h > src.height)
throw new Error('bitblt reading outside image');
if (dx > dst.width || dy > dst.height
|| dx + w > dst.width || dy + h > dst.height)
throw new Error('bitblt writing outside image');
if (deltaX > dst.width || deltaY > dst.height || deltaX + width > dst.width || deltaY + height > dst.height) {
throw new Error('bitblt writing outside image');
}
for (var y = 0; y < h; y++) {
src.data.copy(dst.data,
((dy + y) * dst.width + dx) << 2,
((sy + y) * src.width + sx) << 2,
((sy + y) * src.width + sx + w) << 2
);
for (var y = 0; y < height; y++) {
src.data.copy(dst.data,
((deltaY + y) * dst.width + deltaX) << 2,
((srcY + y) * src.width + srcX) << 2,
((srcY + y) * src.width + srcX + width) << 2
);
}
};
PNG.prototype.bitblt = function(dst, srcX, srcY, width, height, deltaX, deltaY) { // eslint-disable-line max-params
PNG.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY);
return this;
};
PNG.adjustGamma = function(src) {
if (src.gamma) {
for (var y = 0; y < src.height; y++) {
for (var x = 0; x < src.width; x++) {
var idx = (src.width * y + x) << 2;
for (var i = 0; i < 3; i++) {
var sample = src.data[idx + i] / 255;
sample = Math.pow(sample, 1 / 2.2 / src.gamma);
src.data[idx + i] = Math.round(sample * 255);
}
}
}
src.gamma = 0;
}
};
return this;
PNG.prototype.adjustGamma = function() {
PNG.adjustGamma(this);
};
{
"name": "pngjs",
"version": "0.4.0",
"description": "Simple PNG encoder/decoder",
"author": "Kuba Niegowski",
"contributors": [],
"homepage": "https://github.com/niegowski/node-pngjs/",
"keywords" : [
"png"
],
"engines": {
"node": "0.8.x"
},
"main": "./lib/png.js"
"name": "pngjs",
"version": "2.0.0",
"description": "PNG encoder/decoder in pure JS, supporting any bit size & interlace, async & sync with full test suite.",
"contributors": [
"Alexandre Paré",
"Gaurav Mali",
"Kuba Niegowski",
"Luke Page",
"Pietajan De Potter",
"Steven Sojka",
"liangzeng",
"Michael Vogt"
],
"homepage": "https://github.com/lukeapage/pngjs",
"keywords": [
"PNG",
"decoder",
"encoder",
"js-png",
"node-png",
"parser",
"png",
"png-js",
"png-parse",
"pngjs"
],
"engines": {
"node": ">=0.10.0",
"iojs": ">= 1.0.0"
},
"main": "./lib/png.js",
"directories": {
"example": "examples"
},
"scripts": {
"coverage": "istanbul -- cover node_modules/tape/bin/tape test/*-spec.js nolarge",
"coverage-report": "npm run coverage && istanbul report html",
"coveralls": "cat ./coverage/lcov.info | coveralls",
"test": "npm run lint && tape test/*-spec.js | tap-dot && node test/run-compare",
"lint": "eslint lib"
},
"repository": {
"type": "git",
"url": "git://github.com/lukeapage/pngjs2.git"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/lukeapage/pngjs2/issues"
},
"devDependencies": {
"buffer-equal": "0.0.1",
"connect": "^3.4.0",
"eslint": "^1.0.0",
"istanbul": "^0.3.17",
"phantomjs": "^1.9.17",
"serve-static": "^1.10.0",
"tap-dot": "^1.0.0",
"tape": "^4.0.2"
}
}

@@ -1,9 +0,65 @@

About
[![Build Status](https://travis-ci.org/lukeapage/pngjs2.svg?branch=master)](https://travis-ci.org/lukeapage/pngjs2) [![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/pngjs2.svg)](http://badge.fury.io/js/pngjs2)
pngjs
========
Simple PNG encoder/decoder for Node.js with no native dependencies.
Simple PNG encoder/decoder for Node.js with no dependencies.
Based on the original [pngjs](https://github.com/niegowski/node-pngjs) with the follow enhancements.
* Support for reading 1,2,4 & 16 bit files
* Support for reading interlace files
* Support for reading `tTRNS` transparent colours
* Support for writing colortype 2 (RGB) 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 different formats, colortype 0 (greyscale), colortype 3 (indexed color), colortype 4 (greyscale with alpha)
* Synchronous write
Requirements
============
* Async - Node.js 0.10 / 0.12 / IO.js
* Sync - Node.js 0.12 / IO.js
Comparison Table
================
Name | Forked From | Sync | Async | 16 Bit | 1/2/4 Bit | Interlace | Gamma | Encodes | Tested
---------|--------------|------|-------|--------|-----------|-----------|-------|---------|--------
pngjs v2 | pngjs | Read | Yes | Yes | Yes | Yes | Yes | Yes | Yes
node-png | pngjs | No | Yes | No | No | No | Hidden| Yes | Manual
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
Tests
=====
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.
To run the tests, run `node 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.
Installation
===============
```
$ npm install pngjs
$ npm install pngjs --save
```

@@ -42,3 +98,3 @@

Documentation
Async API
================

@@ -48,7 +104,2 @@

### Supported ancillary chunks
- `gAMA` - gamma,
- `tRNS` - transparency (but only for paletted image)
## Class: PNG

@@ -65,3 +116,6 @@ `PNG` is readable and writable `Stream`.

- `deflateStrategy` - compression strategy for delate (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. 2 = color, no alpha, 6 = color & alpha. Default currently 6, but in the future may calculate best mode.
- `inputHasAlpha` - whether the input bitmap has 4 bits per pixel (rgb and alpha) or 3 (rgb - no alpha).

@@ -77,2 +131,3 @@

- `alpha` image contains alpha channel
- `interlace` image is interlaced

@@ -90,3 +145,3 @@

### png.parse(data, [callback])
Parses PNG file data. Alternatively you can stream data to instance of PNG.
Parses PNG file data. Can be `String` or `Buffer`. Alternatively you can stream data to instance of PNG.

@@ -98,2 +153,9 @@ Optional `callback` is once called on `error` or `parsed`. The callback gets

#### Example
```js
new PNG({ filterType:4 }).parse( imageData, function(error, data)
{
console.log(error, data)
});
```

@@ -107,7 +169,33 @@ ### png.pack()

### png.bitblt(dst, sx, sy, w, h, dx, dy)
Helper for image manipulation, copies rectangle of pixels from current image (`sx`, `sy`, `w`, `h`) to `dst` image (at `dx`, `dy`).
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`:
```js
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'));
});
```
### Property: adjustGamma()
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.
```js
fs.createReadStream('in.png')
.pipe(new PNG())
.on('parsed', function() {
this.adjustGamma();
this.pack().pipe(fs.createWriteStream('out.png'));
});
```
### Property: width

@@ -128,22 +216,63 @@ Width of image in pixels

# Sync API
## PNG.sync
### PNG.sync.read(buffer)
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);
```
### PNG.adjustGamma(src)
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);
```
Changelog
============
### 0.4.0 - Jun 05 2013
- fixed reading of destroyed input stream
### 2.0.0 - 08/10/2015
- fixes to readme
- *breaking change* - bitblt on the png prototype now doesn't take a unused, unnecessary src first argument
### 0.4.0-alpha - 29 Nov 2012
- added zlib deflateStrategy option, default to Z_RLE (by pdpotter)
- added possibility to use multiple filters (by pdpotter, modified by niegowski)
### 1.2.0 - 13/09/2015
- support passing colorType to write PNG's and writing bitmaps without alpha information
### 0.3.0-alpha - 23 Aug 2012
- Processing data as Streams, not complete Buffers of data
### 1.1.0 - 07/09/2015
- support passing a deflate factory for controlled compression
### 0.2.0-alpha - 21 Aug 2012
- Input added palette, grayscale, no alpha support
- Better scanline filter selection
### 1.0.2 - 22/08/2015
- Expose all PNG creation info
### 0.1.0-alpha - 19 Aug 2012
- First version
### 1.0.1 - 21/08/2015
- Fix non square interlaced files
### 1.0.0 - 08/08/2015
- 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.
### 0.0.3 - 03/08/2015
- Error handling fixes
- ignore files for smaller npm footprint
### 0.0.2 - 02/08/2015
- Bugfixes to interlacing, support for transparent colours
### 0.0.1 - 02/08/2015
- Initial release, see pngjs for older changelog.
License

@@ -154,4 +283,2 @@ =========

Copyright (c) 2012 Kuba Niegowski
Permission is hereby granted, free of charge, to any person obtaining a copy

@@ -158,0 +285,0 @@ of this software and associated documentation files (the "Software"), to deal

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc