9

I'm using SailsJS (beta). I'm trying to find a way to use graphicsmagick to take the stream parsed by Skipper in SailsJS-beta to resize the image before calling the Skipper-function req.file('inputName').upload().

My goal is to take my large, original image, and resize it before uploading it. Sails beta have introduced the Skipper-file-parser which are poorly documented (at least I don't understand it). Please help me understand how to resize the image before upload.

This works (code in my controller action):

req.file('fileName').upload('storedImage.png', function(err, files){
  // File is now uploaded to storedImage.png
});

What I want is something like:

// Read the file stream into a file upload
var stream = req.file('fileName');

gm(stream).resize(200, 200).write('storedImage.png', function(err){
  // File is now resized to 200x200 px and uploaded to storedImage.png
});

My problem is: how do I properly fetch the stream from req.file('fileName') to send it to gm?

4

2 回答 2

13

这应该适合你:

var Writable = require('stream').Writable;
var resize = require('image-resize-stream')(100); // Or any other resizer

// The output stream to pipe to
var output = require('fs').createWriteStream('storedImage.png');

// Let's create a custom receiver
var receiver = new Writable({objectMode: true});
receiver._write = function(file, enc, cb) {
  file.pipe(resize).pipe(output);

  cb();
};

现在在您的操作中,您只需要使用您的接收器:

req.file('fileName').upload(receiver, function(err, files){
  // File is now resized to 100px width and uploaded to ./storedImage.png
});

我有一种感觉,Skipper 的 API 将会发生很大的变化,但现在这会起作用(使用 v0.1.x)。

更新

具体来说,如果gm用于调整大小,它将是这样的:

var gm = require('gm');
var Writable = require('stream').Writable;

// The output stream to pipe to
var output = require('fs').createWriteStream('storedImage.png');

// Let's create a custom receiver
var receiver = new Writable({objectMode: true});
receiver._write = function(file, enc, cb) {
  gm(file).resize('200', '200').stream().pipe(output);

  cb();
};
于 2014-06-12T16:40:16.607 回答
1

我在使用@bredikhin 解决方案时遇到了问题,所以我深入研究了这个问题,发现这个线程非常有帮助:Uploading files using Skipper with Sails.js v0.10 - how to retrieve new file name

我只是改变了他的一行Uploader

[...]    

file.pipe(outputs);

[...]

进入:

gm(file).resize(200, 200).stream().pipe(outputs);

这就是诀窍。

我写了这个答案,因为它可能对某人有帮助。

于 2015-06-21T09:51:13.480 回答