使用app.js
中的代码,我能够将camerautil.js
中camera()
中生成的raspistill
命令的输出管道传输到可写流。但是,我希望将输出通过管道传输到resize()
中生成的convert
命令,而不是可写流,然后将该命令的stdout管道传输到可写流。
我尝试过的:
var streamOut = fs.createWriteStream('./image.jpg');
camerautil.camera().pipe(camerautil.resize(streamOut, 1, 1));
它抛出以下错误:
events.js:85
throw er; // Unhandled 'error' event
^
Error: Cannot pipe. Not readable.
at WriteStream.Writable.pipe (_stream_writable.js:162:22)
at Object.exports.resize (/home/pi/dev/app/camerautil.js:27:14)
at Object.<anonymous> (/home/pi/dev/app/index3.js:5:37)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
这是我的(工作)代码:
app.js
var camerautil = require('./camerautil'),
fs = require('fs');
var streamOut = fs.createWriteStream('./image.jpg');
camerautil.camera().pipe(streamOut);
camerautil.js
var spawn = require('child_process').spawn,
Stream = require('stream');
exports.camera = function() {
var child = spawn('raspistill', ['-w', 320, '-h', 240, '-n', '-t', 1, '-o', '-']);
var stream = new Stream();
child.stderr.on('data', stream.emit.bind(stream, 'error'));
child.stdout.on('data', stream.emit.bind(stream, 'data'));
child.stdout.on('end', stream.emit.bind(stream, 'end'));
child.on('error', stream.emit.bind(stream, 'error'));
return stream;
}
exports.resize = function(streamIn, width, height) {
var child = spawn('convert', ['-', '-resize', width + 'x' + height, '-']);
var stream = new Stream();
child.stderr.on('data', stream.emit.bind(stream, 'error'));
child.stdout.on('data', stream.emit.bind(stream, 'data'));
child.stdout.on('end', stream.emit.bind(stream, 'end'));
child.on('error', stream.emit.bind(stream, 'error'));
streamIn.pipe(child.stdin);
return stream;
}
我应该提到的是,我正在Raspberry Pi上运行node v0.12.0。raspistill
命令用于使用相机模块拍照。convert
命令是ImageMagick的一部分。
流式传输到gm
模块(Imagemagik的包装器)可能更简单。如果这将安装在树莓派,即.
var gm = require('gm')
gm(camerautil.camera())
.resize('100', '100')
.stream('jpg')
.pipe(streamOut)
https://github.com/aheckmann/gm#streams
经过一番努力,我找到了解决方案。
var camerautil = require('./camerautil'),
fs = require('fs');
var streamOut = fs.createWriteStream('./image.jpg');
camerautil.resize(camerautil.camera(), 1, 1).pipe(streamOut);