From 3f84f2b918805537b2aa70a1362eeeaa84507aec Mon Sep 17 00:00:00 2001 From: XiuYun CHEN Date: Wed, 4 Jun 2025 11:26:13 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E7=A9=BA=E7=99=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../basic/src/main/ets/utils/ChangeUtil.ets | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/commons/basic/src/main/ets/utils/ChangeUtil.ets b/commons/basic/src/main/ets/utils/ChangeUtil.ets index f660514..4effcb6 100644 --- a/commons/basic/src/main/ets/utils/ChangeUtil.ets +++ b/commons/basic/src/main/ets/utils/ChangeUtil.ets @@ -66,10 +66,31 @@ export class ChangeUtil { const buffer = new ArrayBuffer(stat.size); fileIo.readSync(file.fd, buffer); fileIo.closeSync(file); + const buffernew=await ChangeUtil.compression(buffer,"image/jpeg",0.5) // 编码为 Base64 const base64Helper = new util.Base64Helper(); - return base64Helper.encodeToStringSync(new Uint8Array(buffer)); + return base64Helper.encodeToStringSync(new Uint8Array(buffernew)); + } + /** + * 压缩图片 + * @param buffer 二进制 + * @param contentType image/jpeg 保存后的文件格式 + * @param compressionRatio 1 就是 100%, 0.5 就是50% + * @returns + */ + static async compression(buffer: ArrayBuffer, contentType: string, compressionRatio: number = 0.5) { + // 这里判断 1,是因为压缩的时候传了 100%,也会丢失一点精度,所以直接返回了。 + if (compressionRatio == 1) { + return buffer + } + const imageSource: image.ImageSource = image.createImageSource(buffer); + + const imagePackerApi = image.createImagePacker(); + const bf = await imagePackerApi.packing(imageSource, { format: contentType, quality: compressionRatio * 100 }) + + + return bf } /** * 将图片转换为base64字符串