效果图
.wxml
<image src="{{images}}"></image>
<button bindtap="onSaveToPhone" class="btn button-hover" >
保存图片到手机
</button>
.js
Page({
data: {
images: "/images/logo.png",
},
onSaveToPhone(){
var that = this
getApp().onSaveToPhone(that.data.images).then(() => {
console.log('保存成功')
})
},
})
app.js
App({
onLaunch: function () {
},
// 保存图片到手机
onSaveToPhone(image) {
let that = this
return new Promise((resolve, reject) => {
that.getSetting().then((res) => {
// 判断用户是否授权了保存到本地的权限
if (!res.authSetting['scope.writePhotosAlbum']) {
that.authorize().then(() => {
that.saveImageToPhotosAlbum(image).then(() => {
resolve()
})
}).catch(() => {
that.showModal(image).then(() => {
resolve()
})
})
} else {
that.saveImageToPhotosAlbum(image).then(() => {
resolve()
})
}
})
})
},
//打开设置,引导用户授权
onOpenSetting(image) {
var that = this
return new Promise((resolve, reject) => {
wx.openSetting({
success: (res) => {
if (res.authSetting['scope.writePhotosAlbum']) {
that.onSaveToPhone(image).then(() => {// 接受授权后保存图片
resolve()
})
}
}
})
})
},
// 获取用户已经授予了哪些权限
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(image) {
var that = this
return new Promise((resolve, reject) => {
wx.showModal({
title: '检测到您没有打开保存到相册的权限,是否前往设置打开?',
success: (res) => {
if (res.confirm) {
that.onOpenSetting(image).then(() => {// 打开设置页面
resolve()
})
}
}
})
})
},
})
保存图片最好用本地或者自己服务器上的图片,其他图片有些不支持你保存。
有什么问题欢迎评论留言,我会及时回复你的