uni-app:微信小程序:保存图片到相册(hbuilderx 3.7.3)
一,代码:
<template> <view> <view style="margin-left: 20rpx;margin-top: 20rpx; width:710rpx;height:710rpx;background: gray;"> <image class="banner" mode="aspectFit" :show-menu-by-longpress="true" src="https://imgs-qn.iliangcang.com/ware/slider/1908.jpg" /> </view> <button class="shareBtn" type="default" @click="savePosterPath('https://imgs-qn.iliangcang.com/ware/slider/1908.jpg')"> 保存 </button> </view> </template> <script> export default { data() { return { } }, methods: { savePosterPath(url){ let that = this; uni.showLoading({ title: '正在保存图片...' }); //获取用户的当前设置。获取相册权限 uni.getSetting({ success: (res) => { //如果没有相册权限 if (!res.authSetting["scope.writePhotosAlbum"]) { //向用户发起授权请求 uni.authorize({ scope: "scope.writePhotosAlbum", success: () => { //授权成功保存图片到系统相册
uni.hideLoading(); that.saveNetImageToLocal(url); }, //授权失败 fail: () => { uni.hideLoading(); uni.showToast({ title: "未授权保存图片到相册!", }); }, }); } else { that.saveNetImageToLocal(url); } }, fail: (res) => {}, }); },
//保存网络图片到本地 saveNetImageToLocal(url){ uni.downloadFile({ url:url, success:(res)=>{ if (res.statusCode === 200) { uni.saveImageToPhotosAlbum({ filePath: res.tempFilePath, success: (res) => { uni.hideLoading(); return uni.showToast({ title: "保存成功!", }); }, fail: (res) => { uni.hideLoading(); console.log(res.errMsg); return uni.showToast({ title: res.errMsg, }); }, //无论成功失败都走的回调 complete: (res) => {uni.hideLoading();}, }); } else { uni.showToast({ title: '网络错误', }); } } }); }, } } </script> <style> .banner { width:100%; height:100%; } </style>
说明:刘宏缔的架构森林是一个专注架构的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/06/05/uniapp-wei-xin-xiao-cheng-xu-bao-cun-tu-pian-dao-xiang-ce/
对应的源码可以访问这里获取: https://github.com/liuhongdi/
或: https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,可能出现的报错信息:
//授权成功保存图片到系统相册 uni.saveImageToPhotosAlbum({ //图片路径,不支持网络图片路径 filePath: url, success: (res) => { uni.hideLoading(); return uni.showToast({ title: "保存成功!", }); }, fail: (res) => { console.log(res.errMsg); return uni.showToast({ title: res.errMsg, }); }, complete: (res) => {uni.hideLoading();}, });
这里需要注意的是:如果直接传递网络图片的地址给filePath,则系统会报错如下:
saveImageToPhotosAlbum:fail https://img.lhdtest.com/ware/slider/1908.jpg not absolute path
所以在实际应用中需要传递的是一个本地文件地址