0

我正在尝试使用 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);

在此处输入图像描述

4

1 回答 1

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);
于 2016-05-10T13:13:30.197 回答