微信小程序保存图片到手机相册
一次性保存多张图片:https://blog.csdn.net/qq_43764578/article/details/103641190
封装保存图片全局使用:https://blog.csdn.net/qq_43764578/article/details/120826994?spm=1001.2014.3001.5501
.wxml
<image src="{{images}}"></image>
<button wx:if="{{!isAuthSavePhoto}}" bindtap="onSaveToPhone" class="btn button-hover" >
保存图片到手机
</button>
<button wx:else bind:tap="showModal" class="btn button-hover" >
保存图片到手机
</button>
.js
Page({
data: {
images: "/images/logo.png",
isAuthSavePhoto: false,
},
// 保存图片到手机
onSaveToPhone() {
let that = this
that.getSetting().then((res) => {
// 判断用户是否授权了保存到本地的权限
if (!res.authSetting['scope.writePhotosAlbum']) {
that.authorize().then(() => {
that.saveImageToPhotosAlbum(that.data.images)
that.setData({
isAuthSavePhoto: false
})
}).catch(() => {
wx.showToast({
title: '您拒绝了授权',
icon: 'none',
duration: 1500
})
that.setData({
isAuthSavePhoto: true
})
})
} else {
that.saveImageToPhotosAlbum(that.data.images)
}
})
},
//打开设置,引导用户授权
onOpenSetting() {
wx.openSetting({
success: (res) => {
if (!res.authSetting['scope.writePhotosAlbum']) {
wx.showToast({
title: '您未授权',
icon: 'none',
duration: 1500
})
this.setData({// 拒绝授权
isAuthSavePhoto: true
})
} else {// 接受授权
this.setData({
isAuthSavePhoto: false
})
this.onSaveToPhone() // 接受授权后保存图片
}
}
})
},
// 获取用户已经授予了哪些权限
getSetting() {
return new Promise((resolve, reject) => {
wx.getSetting({
success: res => {
resolve(res)
}
})
})
},
// 发起首次授权请求
authorize() {
return new Promise((resolve, reject) => {
wx.authorize({
scope: 'scope.writePhotosAlbum',
success: () => {
resolve()
},
fail: res => { //这里是用户拒绝授权后的回调
reject()
}
})
})
},
// 保存图片到系统相册
saveImageToPhotosAlbum(saveUrl) {
return new Promise((resolve, reject) => {
wx.saveImageToPhotosAlbum({
filePath: saveUrl,
success: (res) => {
wx.showToast({
title: '保存成功',
duration: 1000,
})
resolve()
}
})
})
},
// 弹出模态框提示用户是否要去设置页授权
showModal() {
wx.showModal({
title: '检测到您没有打开保存到相册的权限,是否前往设置打开?',
success: (res) => {
if (res.confirm) {
this.onOpenSetting() // 打开设置页面
}
}
})
},
})
保存图片最好用本地或者自己服务器上的图片,其他图片有些不支持你保存。
有什么问题欢迎评论留言,我会及时回复你的