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
所以在实际应用中需要传递的是一个本地文件地址
三,测试效果
四,查看hbuilderx的版本:

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
2021-02-25 spring boot:为service类做参数化单元测试(spring boot 2.4.3)
2020-02-25 centos8安装sersync为rsync实现实时同步
2020-02-25 rsync安装使用中出现的报错
2020-02-25 centos8环境安装配置rsync
2020-02-25 nfs4使用中的防火墙配置
2020-02-25 centos8安装及配置nfs4