用node.js合并2个图像? [英] Merge 2 images with node.js?
问题描述
我想使用node.js合并2个图像。或者更确切地说,我想在较大的图像上将一个较小的图像放在坐标x,y上。
更精确:我有一个眼镜的图像,一张脸的图像,我想把眼镜放在脸上。
我做了一些谷歌搜索,发现一些图像处理库,但似乎没有人能够合并图像。
I want to merge 2 images using node.js. Or rather, i want to place one smaller image on cordinates x,y on a larger image. Even more precise: I have an image of glasses, and an image of a face and i want to put the glasses on the face. I did some googling, and found some image manipulating libraries, but none seem to be able to merge images.
推荐答案
我用过:
https:// github.com/learnboost/node-canvas
做类似的事情(动态地从组件构建合成图像)。
to do something similar (build a composite image from components on the fly).
效果很好。
以下是一些示例代码:
var Canvas = require('canvas'),
fs = require('fs'),
Image = Canvas.Image;
var _components = [{prefix:'f', count:12},
{prefix:'h', count:12},
{prefix:'i', count:12},
{prefix:'m', count:12}];
var _total = 1;
for (var i=_components.length - 1; i>=0; i--){
_components[i].mult = _total;
_total *= _components[i].count;
}
module.exports.ensureImageExists = function(img, cb){
fs.stat(__dirname + '/../public/images/rb/' + img, function(err, stats){
if (err){
if (err.code == 'ENOENT')
generateImage(img, cb);
else
cb(err);
}
else{
cb();
}
});
}
function generateImage(name, cb){
var re = /rb([0-9]*)\.png/
var num = parseInt(re.exec(name)[1]) % _total;
var parts = [];
for (var i=0; i<_components.length; i++){
var n = Math.floor(num / _components[i].mult);
parts.push(_components[i].prefix + (n + 1));
num -= n * _components[i].mult;
}
var canvas = new Canvas(45, 45),
ctx = canvas.getContext('2d');
drawParts();
function drawParts(){
var part = parts.shift();
if (!part)
saveCanvas();
else {
var img = new Image;
img.onload = function(){
ctx.drawImage(img, 0, 0, 45, 45);
drawParts();
};
img.src = __dirname + '/components/' + part + '.png';
}
}
function saveCanvas(){
canvas.toBuffer(function(err, buf){
if (err)
cb(err);
else
fs.writeFile(__dirname + '/../public/images/rb/' + name, buf, function(){
cb();
});
});
}
}
在这种情况下,组件是根据图像的名称选择,但你显然可以做其他事情。另外,我想你可以根据需要直接将图像流出来 - 我将它写入文件,以便下次请求它时可用。
In this case, the components are selected based upon the name of the image, but you clearly could do otherwise. Also, I imagine you could just stream the image out if you wanted -- I write it to a file so it's available the next time it's requested.
我把这样的路线用于处理这一代:
I put a route like this in to handle the generation:
app.get('/images/rb/:img', requireLogin, function(req, res, next){
//first make sure image exists, then pass along so it is handled
//by the static router
rbgen.ensureImageExists(req.params.img, function(err){
next();
})
});
这篇关于用node.js合并2个图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!