reject(err);
return;
}
const origWidth = size.width;
const origHeight = size.height;
let cropX = 0;
let cropY = 0;
let resizeWidth;
let resizeHeight;
let resizeResult;
// 裁切的宽度和高度做最大最小值限制
if (cropSize > origWidth) {
cropSize = origWidth;
}
else if (cropSize > origHeight) {
cropSize = origHeight;
}
else if (cropSize < minSize) {
cropSize = minSize;
}
// 先计算出等比缩放的尺寸,然后再根据此尺寸计算出裁切位置
if (origWidth > origHeight) {
resizeWidth = cropSize / origHeight * origWidth;
resizeHeight = cropSize;
cropX = Math.floor((resizeWidth - cropSize) / 2);
cropY = 0;
}
else {
resizeHeight = cropSize / origWidth * origHeight;
resizeWidth = cropSize;
cropX = 0;
cropY = Math.floor((resizeHeight - cropSize) / 2);
}
resizeResult = this.resize(resizeWidth, resizeHeight);
resizeResult
.quality(quality)
.interlace('line') // 使用逐行扫描方式
.crop(cropSize, cropSize, cropX, cropY)
.unsharp(2, 0.5, 0.5, 0)
.stream()
.on('end', resolve)
.pipe(writeStream);
});
});
};
上面的 crop 就是对图片进行裁切。当然除了中心裁切,还能延伸出顶部裁切,底部裁切等,相对来说使用场景要少很多。
结语
在服务的实际应用中,还会做一些优化,比如对服务的接口做一些安全限制,确保该接口不会被刷,裁切本身是比较消耗资源的操作。由于裁切操作比较耗资源,那么相同的尺寸应该保证只有一次裁切操作,这样只有第一次请求裁切图片才会真正有裁切操作,后续的访问就直接读取原来就裁切好的实体文件即可。
以上所述是小编给大家介绍的使用 Node.js 实现图片的动态裁切及算法实例代码详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对软件开发网网站的支持!









