运行效果
在之前完成抠图的基础上,再上传一张背景图,将抠图和背景图进行合成,生成新图片保存到本地
功能介绍
利用百度ai人像分隔功能生成的白底图存储到本地之后,提示用户上传一张背景图,将背景图临时路径和白底图路径通过页面跳转参数传递到一个新的页面combine里,在此页面中首先获取屏幕宽度和两张图片的宽高,根据屏幕宽度分别对两张图片进行缩放,利用canvas绘图,首先绘制背景图,然后绘制白底图,完成之后将canvas保存到临时路径中,再将临时路径中的图片存储到本地相册中。
核心代码
参数传递
用户完成背景图片上传之后,将背景图路径和抠图之后保存的路径传递到combine页面,在combine页面中的onload里获取
conmbineTap: function (tempFile){
let that = this
wx.navigateTo({
url: '../combine/combine?imgUrl=' + that.data.filePath + '&img1=' + tempFile
})
},
01
图片尺寸获取
通过微信小程序的getImageInfo方法获取图片的宽高,根据设备尺寸来进行缩放
wx.getImageInfo({
src: that.data.imgUrl,
success: function (res) {
console.log(res)
that.setData({
width1: res.width,
height1: res.height
})
}
})
02图片尺寸处理
if (this.data.clientWidth > this.data.width2) {
var imgwidth1 = this.data.width1
var imgheight1 = this.data.height1
var imgwidth2 = this.data.width2
var imgheight2 = this.data.height2
}
else {
var imgwidth2 = this.data.clientWidth
var imgheight2 = this.data.height2 * imgwidth2 / this.data.width2
if (imgheight2 < this.data.height1)
{
var imgheight1 = imgheight2
var imgwidth1 = this.data.width1 * imgheight1 / this.data.height1
}
else{
var imgheight1 = this.data.height1
var imgwidth1 = this.data.width1 * imgheight1 / this.data.height1
}
}
03图片合成绘图
const ctx = wx.createCanvasContext('shareCanvas')
ctx.drawImage(this.data.img1, 0, 0, this.data.width2, this.data.height2,0,0,imgwidth2, imgheight2)
ctx.drawImage(this.data.imgUrl, 0, 0, this.data.width1, this.data.height1,0,0, imgwidth1, imgheight1)
ctx.draw()
04绘图保存相册
var that = this
wx.showToast({
title: '图片生成中...',
icon: 'loading',
duration: 1000
});
setTimeout(function () {
wx.canvasToTempFilePath({
canvasId: 'shareCanvas',
success: function (res) {
var tempFilePath = res.tempFilePath;
wx.saveImageToPhotosAlbum({
filePath: tempFilePath,
success(res) {
wx.showToast({
title: '保存成功',
icon: 'success'
})
}
})
wx.hideToast()
},
fail: function (res) {
console.log(res);
}
});
}, 500)
如需源码,关注下方公众号,后台回复“图片合成小程序”,感谢阅读,感谢关注
扫码关注一起学习
公众号:teacherli0927