GraphicsMagick是一个免费的开源命令行实用程序,用于处理图像。它是ImageMagick的一个分支,但速度更快,使用的资源更少。如果您计划在Node.js中使用GraphicsMagick,那么npm中有几个可用的包装器可供选择。 但是,有些情况(例如,您不希望依赖第三方模块)可以直接运行该实用程序。 对于这些情况,我将向您展示如何使用child_process Node.js模块在新进程中启动GraphicsMagick。
首先安装GraphicsMagick:
$ apt-get install graphicsmagick
创建自定义GraphicsMagick包装器,保存为gm.js
var GM_PATH = '/usr/bin/gm'; // Path to the GraphicsMagick binary
var TIMEOUT = 60000; // Kill process after N milliseconds
var childProcess = require('child_process');
function spawn(stdin, args, callback) {
var stdout = [];
var stderr = [];
var p = childProcess.spawn(GM_PATH, args);
var timeoutID = setTimeout(function() {
p.kill('SIGKILL');
stderr.push(new Buffer('SIGKILL'));
}, 60000);
p.stdout.on('data', function(data) {
stdout.push(data);
});
p.stderr.on('data', function(data) {
stderr.push(data);
});
p.on('close', function(code) {
clearTimeout(timeoutID);
if (code || stderr.length) {
console.log('code:', code, 'stderr', Buffer.concat(stderr).toString());
return callback();
}
callback(Buffer.concat(stdout));
});
p.stdin.write(stdin);
p.stdin.end();
}
// GraphicsMagick 'convert' command
function convert(image, opt, callback) {
opt = opt ? opt : {};
spawn(image, [
'convert',
opt.srcFormat ? opt.srcFormat + ':-' : '-',
'-resize',
(opt.width ? opt.width : '') + 'x' + (opt.height ? opt.height : ''),
'-quality',
opt.quality ? opt.quality : '100',
opt.format ? opt.format + ':-' : 'PNG:-'
], callback);
}
module.exports = {
convert: convert
};
将以下代码复制粘贴到名为test.js的文件中:
var request = require('request');
var gm = require('./gm'); // Import your module
var url = 'https://upload.wikimedia.org/wikipedia/commons/thumb/a/a8/Tour_Eiffel_Wikimedia_Commons.jpg/553px-Tour_Eiffel_Wikimedia_Commons.jpg';
var out = '/tmp/test.jpg'; // Output file
request({
method: 'GET',
url: url,
encoding: null
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
gm.convert(body, {
srcFormat: null,
width: null,
height: 500,
quality: 90,
format: 'JPEG'
}, function(image) {
require('fs').writeFile(out, image, function(err) {
console.log(err ? err : 'Success!');
});
});
}
});
上述程序将从Web下载大图像,将其大小调整为500px,并将新图像保存到/tmp/test.jpg。
确保在运行test.js之前安装request模块:
$ npm install request
$ node test.js
如果输出Success! 则测试安装成功!
原文链接:https://ubuverse.com/using-graphicsmagick-for-image-manipulation-in-node-js/