uni-app实现高效预览多图base64

	/**
	 * @description 预览多图,解决官方转换时间过长很低效问题
	 * @param {Object} _t 上下文
	 * @param {Object} imgList 要预览的图片列表[{  base64: ... }]
	 * @param {Object} preImgList 存储图片本地路径的指针 ["/_img/yue.png", ""] 注意-这个参数是放入上下文中,无需传,通过上下文可获取到
	 * @param {Number} 预览当前图片的索引
	 */
	previewImgList(_t, imgList = [], index) {
		if (imgList.length == 0) return;
		if (Object.prototype.toString.call(imgList) != "[object Array]") throw new Error(
			"the imgList must be array");
		let preImgList = _t.preImgList || [];
		// #ifdef APP-PLUS
		try {
			if (preImgList.length != imgList.length) {
				let count = 0;
				let arr = [];
				uni.showLoading({
					title: '预览加载中...',
					mask: true
				});
				for (let i = 0, len = imgList.length; i < len; i++) {
					arr.push(_t.$utils.plusBase64ToPath(imgList[i].base64));
				}
				Promise.all(arr).then(paths => {
					uni.hideLoading();
					for (let i = 0, len = paths.length; i < len; i++) {
						preImgList.push(paths[i].target);
					}
					// console.log("preImgList--------------", JSON.stringify(preImgList));
					uni.previewImage({
						urls: preImgList,
						current: index,
						longPressActions: {
							itemList: ['保存图片'],
							success: function(data) {
								const tapIndex = data.tapIndex;
								console.log("tabIndex", tapIndex);
								console.log(JSON.stringify(data));
								if (tapIndex == 0) _t.$utils.saveImg(preImgList[data.index]);
							},
							fail: function(err) {
								console.log(err.errMsg);
							}
						}
					});
				})
			} else {
				uni.previewImage({
					urls: preImgList,
					current: index,
					longPressActions: {
						itemList: ['保存图片'],
						success: function(data) {
							const tapIndex = data.tapIndex;
							console.log("tapIndex", tapIndex);
							console.log(JSON.stringify(data));
							if (tapIndex == 0) _t.$utils.saveImg(preImgList[data.index]);
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				});
			}
		} catch (err) {
			console.log(err);
		}
		// #endif

	},
	/**
	 * @description plus将base64转换为本地图片并返回路径
	 * @param {Object} imageStr 为base64字符串
	 */
	plusBase64ToPath(imageStr) {
		// 保存到本地
		return new Promise((resolve, reject) => {
			let bitmap = new plus.nativeObj.Bitmap("wty");
			bitmap.loadBase64Data(imageStr, function() {
				const tsRandom = new Date().getTime() + "_" + (Math.random() * 1000 >>> 0);
				bitmap.save("_img/" + tsRandom + ".png", {}, function(i) {
					bitmap.clear();
					resolve(i);
				}, function(e) {
					uni.showToast({
						title: "转换异常-1001",
						icon: "none"
					})
					bitmap.clear();
					reject(false);
				});
			}, function() {
				uni.showToast({
					title: "转换异常-1002",
					icon: "none"
				})
				bitmap.clear();
				reject(false);
			});
		})
	}

你可能感兴趣的:(uni-app,javascript,前端)