HarmonyOS鸿蒙Next中如何将PixelMap保存到相册?

HarmonyOS鸿蒙Next中如何将PixelMap保存到相册? 如何将PixelMap保存到相册?

3 回复
import photoAccessHelper from '@ohos.file.photoAccessHelper';
import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import promptAction from '@ohos.promptAction';
import { BusinessError } from '@ohos.base';
import { image } from '@kit.ImageKit';

@Entry
@Component
struct Index {
  @State icon: image.PixelMap | undefined= undefined;
  build() {
    Row() {
      Column({ space: 10 }) {
        SaveButton().onClick(async (event: ClickEvent, result: SaveButtonOnClickResult) => {
          if (result === SaveButtonOnClickResult.SUCCESS) {
            const context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
            this.savePhotoToGallery(context);
          } else {
            promptAction.showToast({ message: '设置权限失败!' })
          }
        })
      }
      .width('100%')
    }
    .height('100%')
    .backgroundColor(0xF1F3F5)
  }

  async savePhotoToGallery(context: common.UIAbilityContext) {
    const imagePackerApi: image.ImagePacker = image.createImagePacker();
    const color: ArrayBuffer = new ArrayBuffer(96); // 96为需要创建的像素buffer大小,取值为:height * width *4
    let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
    this.icon = await image.createPixelMap(color, opts);
    image.createPixelMap(color, opts).then(pixelMap: image.PixelMap => {
      let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }
      imagePackerApi.packing(pixelMap, packOpts)
        .then(async (buffer: ArrayBuffer) => {
          console.info('Succeeded in packing the image.');
          let helper = photoAccessHelper.getPhotoAccessHelper(context)
          let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'png')
          let file = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
          await fs.write(file.fd, buffer)
          await fs.close(file.fd);
          promptAction.showToast({ message: '已保存至相册!' });
        }).catch((error: BusinessError) => {
          console.error('Failed to pack the image..');
        })
    }).catch((error: BusinessError) => {
      console.error('createPixelMap failed.');
    })
  }
}

更多关于HarmonyOS鸿蒙Next中如何将PixelMap保存到相册?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,将PixelMap保存到相册可以通过以下步骤实现:

  1. 获取PixelMap对象:首先确保你已经有一个PixelMap对象,通常是从图像处理或解码过程中获得的。

  2. 创建ImageSource对象:使用PixelMap对象创建一个ImageSource对象。ImageSource是HarmonyOS中用于处理图像的类。

  3. 创建ImagePacker对象:使用ImagePacker类将ImageSource对象打包为图像文件。ImagePacker支持多种图像格式,如JPEG、PNG等。

  4. 保存图像文件:将打包后的图像文件保存到设备存储中。可以使用File类来指定保存路径,通常路径可以设置为相册目录。

  5. 更新媒体库:保存图像文件后,调用MediaLibrary API将文件添加到系统相册中,确保在相册中可见。

以下是代码示例:

import image from '@ohos.multimedia.image';
import fileIo from '@ohos.fileio';
import mediaLibrary from '@ohos.multimedia.mediaLibrary';

async function savePixelMapToAlbum(pixelMap: image.PixelMap) {
    // 创建ImageSource对象
    const imageSource = image.createImageSource(pixelMap);

    // 创建ImagePacker对象
    const imagePacker = image.createImagePacker();

    // 打包为JPEG格式
    const packOptions = { format: 'image/jpeg', quality: 100 };
    const arrayBuffer = await imagePacker.packing(imageSource, packOptions);

    // 保存图像文件
    const context = getContext(this);
    const media = mediaLibrary.getMediaLibrary(context);
    const filePath = `${media.getPublicDirectory(mediaLibrary.DirectoryType.DIR_IMAGE)}/image.jpg`;
    const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
    await fileIo.write(file.fd, arrayBuffer);
    await fileIo.close(file.fd);

    // 更新媒体库
    await media.createAsset(mediaLibrary.MediaType.IMAGE, 'image.jpg', filePath);
}

这段代码展示了如何将PixelMap保存到相册的完整流程。

在HarmonyOS鸿蒙Next中,将PixelMap保存到相册可以通过以下步骤实现:首先,使用ImagePacker将PixelMap转换为ArrayBuffer,然后使用FileIO将数据写入文件,最后通过MediaLibrary将文件添加到系统相册。具体代码如下:

import image from '@ohos.multimedia.image';
import fileio from '@ohos.fileio';
import mediaLibrary from '@ohos.multimedia.mediaLibrary';

async function savePixelMapToGallery(pixelMap) {
    const imagePacker = image.createImagePacker();
    const packOpts = { format: 'image/jpeg', quality: 100 };
    const arrayBuffer = await imagePacker.packing(pixelMap, packOpts);

    const filePath = '/path/to/save/image.jpg';
    await fileio.writeFile(filePath, arrayBuffer);

    const media = mediaLibrary.getMediaLibrary();
    await media.createAsset(mediaLibrary.MediaType.IMAGE, filePath, 'image.jpg');
}

确保在config.json中声明必要的权限,如ohos.permission.WRITE_MEDIAohos.permission.READ_MEDIA

回到顶部