HarmonyOS鸿蒙Next开发时候PixelMap怎么保存成图片文件?

HarmonyOS鸿蒙Next开发时候PixelMap怎么保存成图片文件? 鸿蒙开发时候PixelMap怎么保存成图片文件?

3 回复
import fs from '@ohos.file.fs';
import image from '@ohos.multimedia.image';

if (pixelMap != undefined) {
  // 把pixelMap存到文件
  let imagePackerApi = image.createImagePacker();
  let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 98 };
  let context = currentContext;
  let cacheDir: string = context.cacheDir;
  let dstUri: string = cacheDir + '/IMG_temp.jpg'; // 保存文件uri
  let file: fs.File = fs.openSync(dstUri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  imagePackerApi.packToFile(pixelMap, file.fd, packOpts, (err: BusinessError) => {
    if (err) {
      console.error(`Failed to pack the image to file.code ${err.code},message is ${err.message}`);
    } else {
      console.info('Succeeded in packing the image to file.');
      imagePackerApi.release((err: BusinessError) => {
        if (err) {
          console.error(`Failed to release the image source instance.code ${err.code},message is ${err.message}`);
        } else {
          console.info('Succeeded in releasing the image source instance.');
          fileIo.close(file.fd);
        }
      })
    }
  })
}

更多关于HarmonyOS鸿蒙Next开发时候PixelMap怎么保存成图片文件?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next开发中,将PixelMap保存为图片文件可以通过ImagePacker类实现。首先,确保在项目中引入ohos.media.image包。使用ImagePackercreateImagePacker方法创建一个ImagePacker实例,然后调用initialize方法进行初始化。接着,通过addImage方法将PixelMap添加到ImagePacker中,并使用setOutputFile方法指定输出文件的路径。最后,调用pack方法将PixelMap保存为图片文件。以下是一个示例代码片段:

import image from '@ohos.multimedia.image';
import imagePacker from '@ohos.multimedia.image';

let pixelMap: image.PixelMap;
let filePath: string = "path/to/save/image.png";
let imagePacker: imagePacker.ImagePacker = imagePacker.createImagePacker();
imagePacker.initialize();
imagePacker.addImage(pixelMap);
imagePacker.setOutputFile(filePath);
imagePacker.pack();

在HarmonyOS鸿蒙Next开发中,将PixelMap保存为图片文件可以使用ImagePacker类。首先,创建ImagePacker实例,然后调用createSource方法将PixelMap转换为Source对象,最后使用packToFile方法将Source保存为图片文件。示例代码如下:

ImagePacker imagePacker = ImagePacker.create();
Source source = imagePacker.createSource(pixelMap);
imagePacker.packToFile(source, new File("output.png"));

确保在Manifest文件中声明了存储权限,并在运行时请求权限。

回到顶部