SailsJS(beta)图像中的船长在上传之前调整大小 [英] Skipper in SailsJS (beta) image resize before upload
问题描述
我正在使用SailsJS(测试版)。我试图找到一种方法来使用graphicsmagick在SailsJS-beta中使用Skipper解析的流来调整Skipper函数 req.file('inputName')之前调整图像的大小.upload()
。
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()
.
我的目标是拍摄原始图像,并在上传之前调整大小。 Sails beta引入了Skipper文件解析器,这些解析器文档很少(至少我不理解)。请帮助我了解如何在上传之前调整图片大小。
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
});
我想要的是:
// 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
});
我的问题是:如何从 req.file中正确获取流('fileName')
将它发送给gm?
My problem is: how do I properly fetch the stream from req.file('fileName')
to send it to gm?
推荐答案
这应该适合你:
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();
};
现在你的行动中你必须使用你的接收器:
Now in your action you just have to use your receiver:
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)。
I have a feeling that Skipper's API is going to change, a lot, but this will work for now (with v0.1.x).
更新
具体来说,如果使用 gm
调整大小,它将是这样的:
Specifically, if using gm
for resizing, it'll be something like this:
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();
};
这篇关于SailsJS(beta)图像中的船长在上传之前调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!