我正在尝试设置转换流,以通过GM https://github.com/aheckmann/gm管理图像。所以我可以这样做:
readStream.pipe(resize()).pipe(writeStream);
我已经使用了through2和gm来尝试实现这一点。它可以工作,但只解析一半的图像,留下很大一部分只是灰色。
'use strict';
var fs = require('fs')
, gm = require('gm').subClass({imageMagick: true})
, through2 = require('through2');
let readStream = fs.createReadStream('landscape.jpg');
let writeStream = fs.createWriteStream('landscape-out.jpg');
let resize = function(width, height) {
return through2(function(chunk, enc, callback){
gm(chunk)
.resize(800)
.gravity('Center')
.crop(800, 500, 0, 0)
.stream((err, stdout, stderr) => {
stdout.on('data', chunk => {
this.push(chunk);
});
stdout.on('end', () => {
callback();
});
});
});
}
readStream.pipe(resize()).pipe(writeStream);

答案 0 :(得分:1)
在
through2(function(chunk, enc, callback){
chunk
只是图片的一小部分。
所以你得到的行为似乎很正常,你正在调整图像的大小,而不是图像本身。
这说,在文档中,
// GOTCHA:
// when working with input streams and any 'identify'
// operation (size, format, etc), you must pass "{bufferStream: true}" if
// you also need to convert (write() or stream()) the image afterwards
// NOTE: this buffers the readStream in memory!
var readStream = fs.createReadStream('/path/to/my/img.jpg');
gm(readStream)
.size({bufferStream: true}, function(err, size) {
this.resize(size.width / 2, size.height / 2)
this.write('/path/to/resized.jpg', function (err) {
if (!err) console.log('done');
});
});
但它会将图片缓冲在内存中,所以它不是最佳的。
当您使用imagemagick时,您应该让它管理处理的所有部分。以后fs.readStream,输出。
来自文档
var writeStream = fs.createWriteStream('/path/to/my/reformatted.png');
gm('/path/to/my/img.jpg')
.stream('png')
.pipe(writeStream);