微信小程序保存图片(长按保存and点击保存)

您所在的位置:网站首页 小程序码的图片怎么保存到相册 微信小程序保存图片(长按保存and点击保存)

微信小程序保存图片(长按保存and点击保存)

2024-07-13 10:32| 来源: 网络整理| 查看: 265

一、长按图片保存

只需要image标签给上‘ show-menu-by-longpress=‘1’’属性,就可以实现长按保存功能及长按识别图片中小程序二维码,特别方便

二、点击按钮保存图片至相册

如果调取用户授权访问相册,在用户拒绝后,安卓会出现无法再继续保存的问题,这边给出苹果和安卓都适用的方法,代码如下:

保存到相册 savePoster() { const that = this let fileName = new Date().valueOf(); let filePath = wx.env.USER_DATA_PATH + '/' + fileName + '.jpg' //这边就是为了安卓做的兼容,因为安卓机有可能会将图片地址的后缀名读取为:unknow wx.downloadFile({ url: that.data.imgUrl, //需要保存的图片地址 filePath: filePath, success: function (res) { // 保存图片到系统相册 wx.saveImageToPhotosAlbum({ filePath: filePath, success(data) { let fileMgr = wx.getFileSystemManager() fileMgr.unlink({ filePath: filePath, success() { wx.showToast({ title: '已保存至您的相册', icon: 'none', duration: 1500 }); } }) }, fail(err) { if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") { wx.showModal({ title: '提示', content: '需要您授权保存相册', showCancel: false, success: modalSuccess => { wx.openSetting({ success(settingdata) { if (settingdata.authSetting['scope.writePhotosAlbum']) { console.log('获取权限成功,给出再次点击图片保存到相册的提示。') } else { console.log('获取权限失败,给出不给权限就无法正常使用的提示') } } }) } }) } } }) }, fail: function (res) {} }) }, 如果要调微信授权的保存相册,可以用以下代码: // 保存海报到相册 savePoster() { let that = this wx.getSetting({ success(res) { if (res.authSetting['scope.writePhotosAlbum']) { that.saveImg(); } else if (res.authSetting['scope.writePhotosAlbum'] === undefined) { wx.authorize({ scope: 'scope.writePhotosAlbum', success() { that.saveImg(); }, fail() { that.authConfirm() } }) } else { that.authConfirm() } } }) }, // 授权拒绝后,再次授权提示弹窗 authConfirm() { let that = this wx.showModal({ content: '检测到您没打开保存图片权限,是否去设置打开?', confirmText: "确认", cancelText: "取消", success: function (res) { if (res.confirm) { wx.openSetting({ success(res) { if (res.authSetting['scope.writePhotosAlbum']) { that.saveImg(); } else { wx.showToast({ title: '您没有授权,无法保存到相册', icon: 'none' }) } } }) } else { wx.showToast({ title: '您没有授权,无法保存到相册', icon: 'none' }) } } }); }, //保存图片 saveImg: function () { var that = this; var imgUrl = that.data.imgUrl; //需要保存的图片地址 console.log(imgUrl) wx.downloadFile({ url: imgUrl, success(res) { // 只要服务器有响应数据,就会把响应内容写入文件并进入 success 回调,业务需要自行判断是否下载到了想要的内容 console.log('downloadFileres', res); wx.saveImageToPhotosAlbum({ filePath: res.tempFilePath, success(res) { console.log("保存图片:success"); wx.showToast({ title: '保存成功', }); }, fail: res => { console.log(res); wx.showToast({ title: '保存失败', }); } }) } }) },

希望文章有帮助到您解决问题,瑞思拜~



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3