保存网络图片:
调用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',
});
},
})
},
})
},