uniapp转小程序 图片下载保存

这段代码展示了如何使用uni-app框架保存网络图片和Base64格式的图片到手机相册。首先,通过uni.downloadFile方法下载网络图片并保存,然后使用uni.saveImageToPhotosAlbum将其存入相册。对于Base64格式的图片,先去除data:image前缀,然后写入本地文件,最后保存到相册。同时,代码检查了用户是否授权访问相册,并在未授权时引导用户开启相应权限。
摘要由CSDN通过智能技术生成

 保存网络图片:

调用onSaveimg(imgurl)方法即可

onSaveimg(imgurl) {   //imgurl:图片路径
	uni.showLoading({
		title: '正在保存'
	});
	uni.downloadFile({
	    url: imgurl,
		success: (res) => {
			if (res.statusCode === 200) {
				console.log('下载成功:', res.tempFilePath);
				 uni.saveImageToPhotosAlbum({
					filePath: res.tempFilePath,
					success: function() {
						uni.hideLoading();
						uni.showToast({
							title: '保存成功',
							duration: 2000,
							icon: 'none',
							position: 'bottom',
						});
					},
				});
			}
		}
	});
},

 保存base64格式图片:

调用onBase64(imgurl)方法即可

onBase64(imgurl) { //imgurl:base64格式图片
    uni.showLoading({
		title: '正在保存'
	});
	uni.getSetting({ //获取用户的当前设置
		success: (res) => {
			if (res.authSetting['scope.writePhotosAlbum']) { //验证是否授权可以访问相册
				this.onSaveImage(imgurl);
			} else {
				uni.authorize({ //如果没有授权,向用户发起请求
					scope: 'scope.writePhotosAlbum',
					success: () => {
						this.onSaveImage(imgurl);
					},
					fail: () => {
						uni.showToast({
							title: "请打开保存相册权限,再点击保存相册分享",
							icon: "none",
							duration: 3000
						});
						setTimeout(() => {
							uni.openSetting({ //调起客户端设置,让用户开启访问相册
								success: (res2) => {
									// console.log(res2.authSetting)
								}
							});
						}, 3000);
					}
				})
			}
		}
	})
},
onSaveImage(imgurl) {
	let base64 = imgurl.replace(/^data:image\/\w+;base64,/,"");
    // 微信:wx.env ,跳动音符:tt.env
	let filePath = wx.env.USER_DATA_PATH + '/'+ Math.round(new Date() / 1000) +'.png';
	uni.getFileSystemManager().writeFile({
		filePath: filePath,
		data: base64,
		encoding: 'base64',
		success: res => {
			uni.saveImageToPhotosAlbum({
				filePath: filePath,
				success: function(res2) {
					uni.hideLoading();
					uni.showToast({
						title: '保存成功',
						duration: 2000,
						icon: 'none',
						position: 'bottom',
					});
				},
			})
		},
	})
},

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值