From 073d31347a4c05bb504f7300755d9c710a93de09 Mon Sep 17 00:00:00 2001 From: DCloud_LXH <283700113@qq.com> Date: Tue, 31 Aug 2021 13:43:50 +0800 Subject: [PATCH] fix(App): chooseImage camera.captureImage add compression logic --- .../src/service/api/media/chooseImage.ts | 57 +++++++++++++++++-- 1 file changed, 52 insertions(+), 5 deletions(-) diff --git a/packages/uni-app-plus/src/service/api/media/chooseImage.ts b/packages/uni-app-plus/src/service/api/media/chooseImage.ts index be61a0c40..21712424d 100644 --- a/packages/uni-app-plus/src/service/api/media/chooseImage.ts +++ b/packages/uni-app-plus/src/service/api/media/chooseImage.ts @@ -1,5 +1,6 @@ import { TEMP_PATH } from '../constants' import { warpPlusErrorCallback } from '../../../helpers/plus' +import { getFileName } from '../../../helpers/file' import { API_TYPE_CHOOSE_IMAGE, API_CHOOSE_IMAGE, @@ -26,6 +27,30 @@ function getFileInfo(filePath: string): Promise { }) } +function compressImage(tempFilePath: string): Promise { + const dst = `${TEMP_PATH}/compressed/${Date.now()}_${getFileName( + tempFilePath + )}` + return new Promise((resolve) => { + plus.nativeUI.showWaiting() + plus.zip.compressImage( + { + src: tempFilePath, + dst, + overwrite: true, + }, + () => { + plus.nativeUI.closeWaiting() + resolve(dst) + }, + () => { + plus.nativeUI.closeWaiting() + resolve(tempFilePath) + } + ) + }) +} + type File = { path: string size: number @@ -61,11 +86,33 @@ export const chooseImage = defineAsyncApi( function openCamera() { const camera = plus.camera.getCamera() - camera.captureImage((path) => successCallback([path]), errorCallback, { - filename: TEMP_PATH + '/camera/', - resolution: 'high', - crop, - }) + camera.captureImage( + (path) => { + // fix By Lxh 暂时添加拍照压缩逻辑,等客户端增加逻辑后修改 + // 判断是否需要压缩 + if (sizeType && sizeType.includes('compressed')) { + return getFileInfo(path) + .then(({ size }) => { + // 压缩阈值 0.5 兆 + const THRESHOLD = 1024 * 1024 * 0.5 + return size && size > THRESHOLD + ? compressImage(path).then((dstPath) => + successCallback([dstPath]) + ) + : successCallback([path]) + }) + .catch(errorCallback) + } + + return successCallback([path]) + }, + errorCallback, + { + filename: TEMP_PATH + '/camera/', + resolution: 'high', + crop, + } + ) } function openAlbum() { -- GitLab