pngjs/lib/packer-async.js

63 lines
2.1 KiB
JavaScript

'use strict';
var util = require('util');
var Stream = require('stream');
var zlib = require('zlib');
var constants = require('./constants');
var Packer = require('./packer');
var PackerAsync = 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;
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');
}
this._packer = new Packer(options);
this._deflate = options.deflateFactory({
chunkSize: options.deflateChunkSize,
level: options.deflateLevel,
strategy: options.deflateStrategy
});
this.readable = true;
};
util.inherits(PackerAsync, Stream);
PackerAsync.prototype.pack = function(data, width, height, gamma) {
// Signature
this.emit('data', new Buffer(constants.PNG_SIGNATURE));
this.emit('data', this._packer.packIHDR(width, height));
if (gamma) {
this.emit('data', this._packer.packGAMA(gamma));
}
var filteredData = this._packer.filterData(data, width, height);
// compress it
this._deflate.on('error', this.emit.bind(this, 'error'));
this._deflate.on('data', function(compressedData) {
this.emit('data', this._packer.packIDAT(compressedData));
}.bind(this));
this._deflate.on('end', function() {
this.emit('data', this._packer.packIEND());
this.emit('end');
}.bind(this));
this._deflate.end(filteredData);
};