300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 微信小程序保存图片到手机相册(封装全局使用)

微信小程序保存图片到手机相册(封装全局使用)

时间:2024-01-14 07:55:21

相关推荐

微信小程序保存图片到手机相册(封装全局使用)

效果图

.wxml

<image src="{{images}}"></image><button bindtap="onSaveToPhone" class="btn button-hover" >保存图片到手机</button>

.js

Page({data: {images: "/images/logo.png",},onSaveToPhone(){var that = thisgetApp().onSaveToPhone(that.data.images).then(() => {console.log('保存成功')})},})

app.js

App({onLaunch: function () {},// 保存图片到手机onSaveToPhone(image) {let that = thisreturn 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 = thisreturn 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 = thisreturn new Promise((resolve, reject) => {wx.showModal({title: '检测到您没有打开保存到相册的权限,是否前往设置打开?',success: (res) => {if (res.confirm) {that.onOpenSetting(image).then(() => {// 打开设置页面resolve() })}}})})},})

保存图片最好用本地或者自己服务器上的图片,其他图片有些不支持你保存。

有什么问题欢迎评论留言,我会及时回复你的

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。