想要将图片保存到手机相册我将它分为以下几步:
1. 需要知道你要保存的图片地址
如:image = https://img-blog.csdnimg.cn/20181205101507448.png 注:需要把图片服务器的域名加到downloadFile 合法域名里面
这里会有个问题:微信是不能直接读到我们的图片路径的,我们需要做如下操作,微信会返回一个他们规则的图片地址给你。
返回的地址类似于 -->> http://tmp/wx4dab63941810c315XXXXe0102472ca8f662.jpg
wx.getImageInfo({
src: image,
success: function (res) {
imageWX = res.path
}
})
2. 调用官方提供的方法
wx.saveImageToPhotosAlbum({
filePath: imageWX,
success: (res) => {
that.hideModal();
that.hideMoments();
wx.showToast({
title: "已保存到相册",
icon: 'none',
duration: 2000,
mask: true
})
}
3. 如果用户不小心拒接授权的话再次保存图片会报:saveImageToPhotosAlbum:fail auth deny(意思就是没有授权)
这个时候不要慌,我们可以重新打开设置窗口,再设置一下就ok了
wx.openSetting({
success(settingdata) {
console.error(settingdata)
if (settingdata.authSetting["scope.writePhotosAlbum"]) {
console.error("获取权限成功,再次点击图片保存到相册")
} else {
console.error("获取权限失败")
}
}
})
下面奉上具体的代码:
//保存至相册
saveImageToPhotosAlbum: function () {
var that = this
var value = that.data.tempFilePath;// 你的图片路径
if (value != undefined && value != "") {
wx.saveImageToPhotosAlbum({
filePath: value,
success: (res) => {
that.hideModal();
that.hideMoments();
wx.showToast({
title: "已保存到相册",
icon: 'none',
duration: 2000,
mask: true
})
},
fail: function (res) {
console.error(res)
//首次保存会询问你是否授权,选是就好了
// if (res.errMsg == "saveImageToPhotosAlbum:fail auth deny") {
console.error("打开设置窗口");
wx.openSetting({
success(settingdata) {
console.error(settingdata)
if (settingdata.authSetting["scope.writePhotosAlbum"]) {
console.error("获取权限成功,再次点击图片保存到相册")
} else {
console.error("获取权限失败")
}
}
})
// }
}
})
}
},
总结:
· 微信保存图片到相册的时候会先获取你的权限(是否授权)。
· 微信只认自己