通过图形魔术管道图像只完成了一半

Pipe image through graphics magic only half complete

我正在尝试设置转换流以通过 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);

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);