上篇文章有讲到Nodejs使用sharp将多个图片合成一个图片,但是对于有的图片可能会先进行旋转,然后再参与图片的合成,这时我们就需要针对单个图片进行旋转的处理。
在sharp提供的官方文档中提供了rotate来进行图片旋转,合成的具体步骤如下所示:
const data = {
"title": "Sharp合成图片", // 图片名称
"width": 1960, // 画板宽度
"height": 1208, // 画板高度
"layers": [
{
"id": 1,
"url":"1.jpg", // 根据地址项目中要能够找到该路径的图片
"left": 0,
"top": 0,
"rotate": 0,
"blend": "over", // 图片混合模式-如不需指定则不用添加该参数
},
{
"id": 2,
"url":"2.jpg",
"left": 100,
"top": 500,
"rotate": 40,
"blend": "over",
}
]
}
// 指定输入文件路径
const url = `${__dirname}/image/out/${data['title']}.jpg`
// 组装合成数据,此处需要使用Promise.all,等待数据组装完成再进行下步操作
const info = await Promise.all(data['layers']).then(async (item) => {
const result = [];
for (let i = 0; i < item.length; i++) {
let resultInfo = [];
// 图片旋转处理
if (data['layers'][i]['rotate'] !== 0) {
// 获取旋转图片信息
const sharpInfo = await sharp(data['layers'][i]['url']).metadata();
// 旋转后的图片地址
const outPath = `${__dirname}/image/rotate/${id}.png`;
// 旋转图片
await sharp(imageData).rotate(rotate, { background: 'rgba(0,0,0,0)' }).toFile(outPath);
// 获取旋转后的图片信息
const sharpRotateInfo = await sharp(data['layers'][i]['url']).metadata(outPath);
// 获取中心点
const centerLeft = sharpInfo.width / 2 + left;
const centerTop = sharpInfo.height / 2 + top;
// 设置旋转中心点
const rotateLeft = centerLeft - sharpRotateInfo.width / 2;
const rotateTop = centerTop - sharpRotateInfo.height / 2;
data['layers'][i]['url'] = outPath;
data['layers'][i]['top'] = parseInt(String(rotateTop), 10);
data['layers'][i]['left'] = parseInt(String(rotateLeft), 10);
}
result.push({
input: data['layers'][i]['url'],
blend: data['layers'][i]['blend'],
top: data['layers'][i]['top'],
left: data['layers'][i]['left'],
});
}
return result;
});
// 合成图片
await sharp({ // 创建画板
create: {
data['width'], // 画板宽度
data['height'], // 画板高度
channels: 4,
background: { r: 255, g: 255, b: 255, alpha: 1 } // 画板背景色
},
})
.composite(info)
.toFile(url);