这个问题背后的背景是我正在获取一个图像缓冲区,用pngquant对其进行压缩,然后将压缩图像传递给响应。就像是:
// https://www.npmjs.com/package/pngquant
const PngQuant = require('pngquant');
// start with base64-encoded png image data:
var base64data = '.......';
// then create buffer from this, as per:
// https://stackoverflow.com/a/28440633/4070848
// https://stackoverflow.com/a/52257416/4070848
var imgBuffer = Buffer.from(base64data, 'base64');
// set up pngquant...
const optionsArr = [ ..... ];
const myPngQuanter = new PngQuant(optionsArr);
// convert buffer into stream, as per:
// https://stackoverflow.com/a/16044400/4070848
var bufferStream = new stream.PassThrough();
bufferStream.end(imgBuffer);
// pipe the image buffer (stream) through pngquant (to compress it) and then to res...
bufferStream.pipe(myPngQuanter).pipe(res);
我想确定 pngquant 操作实现的压缩比。我可以很容易地找到起始尺寸:
const sizeBefore = imgBuffer.length;
我还需要压缩流的大小。此外,在将流传输到目标之前,此信息必须可用,res
因为我需要res
根据压缩统计信息添加标头。
为此sizeAfter
,我尝试了length-stream 模块,您可以在其中将侦听器插入管道(在myPngQuanter
和之间res
)以确定它通过时的长度。虽然这似乎确实可以确定压缩流的长度,但不会及时将任何标头添加到res
. 我也尝试过stream-length,但根本无法让它工作。
任何帮助表示赞赏。