如何将像素点保存到图片文件
=============

首先，将像素点信息转换为imageSource；然后，使用packToData方法将imageSource转换为图片格式；最后，通过文件管理模块将图片数据保存到应用沙箱目录。示例代码如下：

import { fileIo } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { image } from '@kit.ImageKit';
import { resourceManager } from '@kit.LocalizationKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct SavePixelMapToImageFile {
  @State saveButtonOptions: SaveButtonOptions = {
    icon: SaveIconStyle.FULL\_FILLED,
    text: SaveDescription.SAVE,
    buttonType: ButtonType.Capsule
  };
  @State pixel: image.PixelMap | undefined = undefined;
  @State imageResource: image.ImageSource | undefined = undefined;
  private context = this.getUIContext().getHostContext() as common.UIAbilityContext;

  async aboutToAppear() {
    const resourceMgr: resourceManager.ResourceManager = this.context.resourceManager;
   _ // 'test. jpeg 'is the name of the image file in the rawfile directory, which can be modified and used as needed._
    const fileData: Uint8Array = await resourceMgr.getRawFileContent('test.png');
    let buffer = new Uint8Array(fileData).buffer as object as ArrayBuffer;
    this.imageResource = image.createImageSource(buffer);
    let opts: image.DecodingOptions = { editable: true };
    this.pixel = await this.imageResource.createPixelMap(opts);
  }

  async savePixelMapToSandbox() {
    try {
    _  // Convert to JPEG image format._
      let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 98 };
      const imagePackerObj: image.ImagePacker = image.createImagePacker();
     _ // Encode Pixelmap into an ArrayBuffer using packToData._
      let ArrayBuffer: ArrayBuffer = await imagePackerObj.packToData(this.imageResource, packOpts);
   _   // Use context.filesDir to retrieve the application sandbox file directory and generate a unique file name._
      let filePath: string = this.context.filesDir + \`/${Date.now()}.jpeg\`;
   _   // Open files in read and create mode to obtain file descriptors._
      const file = await fileIo.open(filePath, fileIo.OpenMode.READ\_WRITE | fileIo.OpenMode.CREATE);
  _    // Write ArrayBuffer data to a sandbox file._
      await fileIo.write(file.fd, ArrayBuffer);
      await fileIo.close(file.fd);
      console.info(\`The image has been successfully saved to the sandbox path: ${filePath}\`);
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error(\`Save failed, error code: ${err.code}, message: ${err.message}\`);
    }
  }

  build() {
    Column() {
      Image(this.pixel)
        .objectFit(ImageFit.None)
        .width('100%')
        .height('30%')

      SaveButton()
        .onClick(async (event, result: SaveButtonOnClickResult) => {
          if (result === SaveButtonOnClickResult.SUCCESS) {
            this.savePixelMapToSandbox();
          }
        })
    }
    .width('100%')
    .height('100%')
    .alignItems(HorizontalAlign.Center)
    .justifyContent(FlexAlign.Center)
  }
}

**参考链接**

[图片处理](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-image)，[文件管理](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-file-fs)