微信小程序:设置缓存的背景图片

679 阅读2分钟

采用uniapp写小程序 , 下面的uni.xxx等api 替换为 wx.xxx即可

如果你有想给用户自定义能力的话一定会有自定义背景的选项 .

怎么做呢 ?

思路

用户选择本地图片 => 将临时地址变为持久储存 => 将持久储存地址存入缓存

使用到各个api和在此功能中的作用

  • uni.chooseImage 使用户选择图片并返回临时文件地址
  • uni.saveFile 接受临时文件地址并将临时文件保存为持久文件 , 返回持久文件地址
  • uni.setStorage 设置持久文件地址
  • uni.getStorage 获取持久文件地址
  • uni.removeSavedFile 移除文件
  • compressImage 压缩jpg图片 , 非必须

代码如下

//获取背景图片的一个业务
try{
				const {tempFilePaths: [path]} = await becomePromise(uni.chooseImage,{count: 1},'chooseImage');
				const {savedFilePath:newPath} = await becomePromise(uni.saveFile,{tempFilePath:path},'saveFile');
				const backgroundImage = uni.getStorageSync('backgroundImage','');
				if(backgroundImage!='') uni.removeStorageSync(backgroundImage);
				await becomePromise(uni.setStorage,{key: 'backgroundImage',data: newPath},'setStorage');
				this.setBackground(newPath);
			}catch(e){
				if(e[1] == 'chooseImage') this.fail('系统不支持选择图片');
				else if(e[1] == 'saveFile') this.fail('保存图片失败');
				else if(e[1] == 'setStorage') this.fail('保存图片路径失败,请清除缓存');
			}

流程如下:

用户选择 -> 缓存取出原储存图片地址并删除图片文件 -> 持久储存用户选择图片 -> 存入缓存 .

**问题:为什么要uni.removeSavedFile 移除文件? **

微信小程序有文件储存上限 , 应该是 10mb 所以如果不移除,用户多选择几次 , 就达到储存上限了

显示部分

使用 background-image 作为背景

坑: ios 小程序上 background-image 无法引用本地图片

解决方法: background-image css3 中新增解析base64字符显示图片

语法如下

background-image:url(data:image;base64,base64string)

我们将本地图片转换为base64字符串再给css去解析

api
  • uni.getFileSystemManager().readFile
uni.getFileSystemManager().readFile({
							filePath: this.backgroundImage,//这个是本地图片地址
							encoding: 'base64',//返回base64字符串
							success: res => (this.backgroundString = 'background-image:url(data:image;base64,' + res.data + ');')
						});

注意:请判断设备的系统只在ios使用这个方法且采用异步函数 , 因为解析成base64是非常消耗性能的 ; 安卓上采用普通的background-image:url(path) 即可

拓展:给背景添加黑色蒙层

css3支持多背景 支持线性渐变;

background-image : linear-gradient(rgba(0,0,0,.3) 0%, rgba(0,0,0,.3) 100%),url(path);
background-position : center center ,center center