fa6fb80d19
Co-authored-by: Cursor <cursoragent@cursor.com>
35 lines
1007 B
TypeScript
35 lines
1007 B
TypeScript
import Taro from '@tarojs/taro';
|
|
|
|
const MAX_BYTES = 10 * 1024 * 1024;
|
|
|
|
/** 小程序临时文件超过 10MB 时用 compressImage 压缩后再上传 */
|
|
export async function compressWeappImageIfNeeded(tempFilePath: string): Promise<string> {
|
|
if (process.env.TARO_ENV !== 'weapp') return tempFilePath;
|
|
|
|
let path = tempFilePath;
|
|
let size = await getFileSize(path);
|
|
if (size <= MAX_BYTES) return path;
|
|
|
|
const qualities = [80, 65, 50, 40];
|
|
for (const quality of qualities) {
|
|
const res = await Taro.compressImage({ src: path, quality });
|
|
path = res.tempFilePath;
|
|
size = await getFileSize(path);
|
|
if (size <= MAX_BYTES) return path;
|
|
}
|
|
|
|
if (size > MAX_BYTES) {
|
|
throw new Error('图片压缩后仍超过 10MB,请换一张较小的图片');
|
|
}
|
|
return path;
|
|
}
|
|
|
|
async function getFileSize(filePath: string): Promise<number> {
|
|
try {
|
|
const info = await Taro.getFileInfo({ filePath });
|
|
return typeof info.size === 'number' ? info.size : 0;
|
|
} catch {
|
|
return 0;
|
|
}
|
|
}
|