uniapp 实现base64格式图片保存到相册
开发过程中的一个需求:后端返回的一个base64格式的图片显示在页面上,需要点击保存该图片到系统相册。
一、触发按钮保存图片到本地
uni-app将图片存入系统的官方api是 uni.saveImageToPhotosAlbum(OBJECT),需要给定一个文件路径filePath,但是这个路径我们是没办法拿到的。
解决思路:需要用到Bitmap,把base64转成bitmap文件对象,保存到系统相册(但是此时某些手机上无法显示出来,其实是保存成功的),然后使用uni.saveImageToPhotoAlbum方法将图片成功保存并显示。
1、Bitmap是原生图片对象,其有个方法是loadBase64Data;于是我们首先创建一个bitmap对象:
2、然后使用loadBase64Data将base64字符串转换为bitmap文件对象:
3、调用bimap.save方法,将图片文件存入手机存储(记得bitmap.clear(),比较占内存)
4、uni.saveImageToPhotoAlbum方法将图片成功保存并显示
整体代码如下:
saveHeadImgFile() { let base64 = this.qrImgUrl; const bitmap = new plus.nativeObj.Bitmap("test"); bitmap.loadBase64Data(base64, function() { const url = "_doc/" + new Date().getTime() + ".png"; // url为时间戳命名方式 console.log('saveHeadImgFile', url) bitmap.save(url, { overwrite: true, // 是否覆盖 // quality: 'quality' // 图片清晰度 }, (i) => { uni.saveImageToPhotosAlbum({ filePath: url, success: function() { uni.showToast({ title: '图片保存成功', icon: 'none' }) bitmap.clear() } }); }, (e) => { uni.showToast({ title: '图片保存失败', icon: 'none' }) bitmap.clear() }); }, (e) => { uni.showToast({ title: '图片保存失败', icon: 'none' }) bitmap.clear() }); }
二、长按保存到本地
1、封装一个组件:saveImg.vue
<template> <!-- 预览图片 --> <view class="preview-photo-box flex-box"> <view class="item tc"> <image class="receive-qrcode-img" :src="url" mode="widthFix" @longtap="toSave"></image> </view> </view> </template> <script> export default { props: { url: { type: String, default: '' } }, data() { return {}; }, methods: { hide() { this.$emit('hide'); }, saveImgFile() { let base64 = this.url; const bitmap = new plus.nativeObj.Bitmap("test"); bitmap.loadBase64Data(base64, function() { const url = "_doc/" + new Date().getTime() + ".png"; // url为时间戳命名方式 console.log('saveHeadImgFile', url) bitmap.save(url, { overwrite: true, // 是否覆盖 // quality: 'quality' // 图片清晰度 }, (i) => { uni.saveImageToPhotosAlbum({ filePath: url, success: function() { uni.showToast({ title: '图片保存成功', icon: 'none' }) bitmap.clear() } }); }, (e) => { uni.showToast({ title: '图片保存失败', icon: 'none' }) bitmap.clear() }); }, (e) => { uni.showToast({ title: '图片保存失败', icon: 'none' }) bitmap.clear() }); }, toSave() { uni.showModal({ title: '图片保存', content: '确定要保存图片吗', success: e => { if (e['confirm']) { this.saveImgFile(); } } }); } } }; </script> <style lang="scss"> .preview-photo-box { width: 100%; height: 100%; z-index: 99; justify-content: center; align-items: center; .item { .receive-qrcode-img { position: relative; z-index: 2; width: 224upx; height: 224upx; margin: 0 auto; } } } </style>