【问题标题】:In this node.js image module, which should I use? (readStream or from path?)在这个 node.js 图像模块中,我应该使用哪个? (读取流还是从路径?)
【发布时间】:2012-01-13 07:30:30
【问题描述】:

什么是“流”?我应该使用以下哪个最快? 有没有办法从内存中打开它,比如缓冲区?

// can provide either a file path or a ReadableStream
// (from a local file or incoming network request)
var readStream = fs.createReadStream('/path/to/my/img.jpg');
gm(readStream, 'img.jpg')
.write('/path/to/reformat.png', function (err) {
  if (!err) console.log('done');
});

// can also stream output to a ReadableStream
// (can be piped to a local file or remote server)
gm('/path/to/my/img.jpg')
.resize('200', '200')
.stream(function (err, stdout, stderr) {
  var writeStream = fs.createWriteStream('/path/to/my/resized.jpg');
  stdout.pipe(writeStream);
});

// pass a format or filename to stream() and
// gm will provide image data in that format
gm('/path/to/my/img.jpg')
.stream('png', function (err, stdout, stderr) {
  var writeStream = fs.createWriteStream('/path/to/my/reformated.png');
  stdout.pipe(writeStream);
});

// combine the two for true streaming image processing
var readStream = fs.createReadStream('/path/to/my/img.jpg');
gm(readStream, 'img.jpg')
.resize('200', '200')
.stream(function (err, stdout, stderr) {
  var writeStream = fs.createWriteStream('/path/to/my/resized.jpg');
  stdout.pipe(writeStream);
});

// 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 temporarily buffers the image stream in Node memory
var readStream = fs.createReadStream('/path/to/my/img.jpg');
gm(readStream, 'img.jpg')
.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');
  });
});

【问题讨论】:

    标签: image memory node.js stream


    【解决方案1】:

    流一次从文件中读取一个数据块。它对于读取大文件而不必将全部内容存储在内存中很有用。

    如果您已经打开了一个流并且它还没有开始发送数据,请传递该流。否则给它一个路径,它必须打开一个新的流。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-16
      • 1970-01-01
      • 2012-03-01
      • 1970-01-01
      • 2011-10-17
      • 1970-01-01
      • 1970-01-01
      • 2021-08-10
      相关资源
      最近更新 更多