HarmonyOS 鸿蒙Next中我想做一个循环压缩图片的功能

HarmonyOS 鸿蒙Next中我想做一个循环压缩图片的功能

首先我需要判断图片是否大于多少M

然后要循环压缩到多少M

怎么做

4 回复

你看这个代码是不是满足你的要求:

[https://ohpm.openharmony.cn/#/cn/detail/@yanq%2Fsipcompass](https://ohpm.openharmony.cn/#/cn/detail/@yanq%2Fsipcompass)

更多关于HarmonyOS 鸿蒙Next中我想做一个循环压缩图片的功能的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中实现图片循环压缩,可使用image模块的ImagePackerImageSource。先用ImageSource.createFromFile获取源图片,通过ImagePacker设置压缩参数(如quality: 75%),调用packToFile输出压缩文件。循环处理时,建议用for循环控制压缩次数,每次迭代更新输出路径。注意在ArkTS中使用异步处理(async/await)避免阻塞UI。循环中需检测图片尺寸,当宽高低于阈值时终止循环。典型代码结构:

let imageSource = image.createImageSource(filePath);
let packer = image.createImagePacker();
for(let i=0; i<maxLoops; i++){
  await packer.packing(imageSource, outputPath, {quality:75});
}

在HarmonyOS Next中实现图片循环压缩功能,可以按照以下步骤实现:

  1. 判断图片大小:
import fileio from '@ohos.fileio';

async function getFileSize(filePath: string): Promise<number> {
    const stat = await fileio.stat(filePath);
    return stat.size; // 返回字节数
}
  1. 压缩图片核心代码:
import image from '@ohos.multimedia.image';

async function compressImage(inputPath: string, outputPath: string, quality: number): Promise<void> {
    const imageSource = await image.createImageSource(inputPath);
    const imagePacker = image.createImagePacker();
    
    const options = {
        format: "image/jpeg",
        quality: quality // 0-100
    };
    
    await imagePacker.packing(imageSource, options, outputPath);
}
  1. 循环压缩逻辑:
async function compressUntilSize(inputPath: string, outputPath: string, targetSizeMB: number): Promise<void> {
    const targetBytes = targetSizeMB * 1024 * 1024;
    let currentQuality = 90; // 初始质量
    
    while (currentQuality > 10) { // 设置最低质量阈值
        await compressImage(inputPath, outputPath, currentQuality);
        
        const compressedSize = await getFileSize(outputPath);
        if (compressedSize <= targetBytes) {
            break;
        }
        
        currentQuality -= 10; // 每次降低10%质量
    }
}

使用示例:

const input = "path/to/input.jpg";
const output = "path/to/output.jpg";
const maxSizeMB = 1; // 目标1MB

compressUntilSize(input, output, maxSizeMB).then(() => {
    console.log("压缩完成");
});

注意事项:

  1. 需要申请ohos.permission.READ_MEDIA和ohos.permission.WRITE_MEDIA权限
  2. 建议添加压缩次数限制防止无限循环
  3. 大文件处理建议使用Worker线程避免阻塞UI
回到顶部