HarmonyOS 如何转ArrayBuffer?

从相册选择了一张图片,现在业务上需要将图片转为ArrayBuffer类型,怎么转?

阅读 593
1 个回答

参考示例:

import photoAccessHelper from '@ohos.file.photoAccessHelper';
import image from '@ohos.multimedia.image';
import fs from '@ohos.file.fs';
import { buffer } from '@kit.ArkTS';

@Entry
@Component
struct Page2 {
  @State resultBase64Str: string = '';
  @State getAlbum: string = '显示相册中的图片';
  @State pixel: image.PixelMap | undefined = undefined;
  @State albumPath: string = '';
  @State photoSize: number = 0;

  async getPictureFromAlbum() {
    // 拉起相册,选择图片
    let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
    PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
    PhotoSelectOptions.maxSelectNumber = 1;
    let photoPicker = new photoAccessHelper.PhotoViewPicker();
    let photoSelectResult: photoAccessHelper.PhotoSelectResult = await photoPicker.select(PhotoSelectOptions);
    this.albumPath = photoSelectResult.photoUris[0];
    console.info('albumPath: ' + this.albumPath)
    // 读取图片为buffer
    const file = fs.openSync(this.albumPath, fs.OpenMode.READ_WRITE);
    this.photoSize = fs.statSync(file.fd).size;
    console.info('Photo Size: ' + this.photoSize);
    let buffer1 = new ArrayBuffer(this.photoSize);
    fs.readSync(file.fd, buffer1);
    let base64Str: string = buffer.from(buffer1).toString('base64')
    let resultBase64Str = "data:image/png;base64," + base64Str
    this.resultBase64Str = resultBase64Str
    fs.closeSync(file);
    // 解码成PixelMap
    const imageSource = image.createImageSource(buffer1);
    console.log('imageSource: ' + JSON.stringify(imageSource));
    this.pixel = await imageSource.createPixelMap({});
  }

  build() {
    Scroll() {
      Column() {
        Text('获取图片')
          .onClick(async () => {
            await this.getPictureFromAlbum()
          })
        // Image(this.pixel)
        Image(this.resultBase64Str).width(40).height(40)
        Text(this.resultBase64Str)
      }
    }
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进