HarmonyOS pickerResult.resultUri返回的照片如何裁剪大小并转base64数据?

HarmonyOS
3天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
superinsect

import { fileIo, picker } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
import { util } from '@kit.ArkTS';

@Entry
@Component
struct Index {
  @State selectedUri: string = ''
  @State cropped: PixelMap | undefined = undefined
  private uri:string = ''

  private async decodeImage(uri: string) {
    try {
      let file = fileIo.openSync(uri, fileIo.OpenMode.READ_ONLY)
      const imageSourceApi = image.createImageSource(file.fd)
      imageSourceApi.getImageInfo(0, (error: BusinessError, imageInfo) => {
        if (imageInfo == undefined) {
          // log.e(error)
        }
        console.log(`imageInfo:  ${JSON.stringify(imageInfo)}`)
      })
      return await imageSourceApi.createPixelMap()
    } catch (error) {
      // log.e(error)
      return undefined
    }
  }

  selectPhoto() {
    const photoSelectOptions = new picker.PhotoSelectOptions();
    const photoViewPicker = new picker.PhotoViewPicker();
    photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; // 过滤选择媒体文件类型为IMAGE
    photoSelectOptions.maxSelectNumber = 1; // 选择媒体文件的最大数目
    photoViewPicker.select(photoSelectOptions).then((photoSelectResult: picker.PhotoSelectResult) => {
      this.selectedUri = photoSelectResult.photoUris[0]
      //裁剪
      this.crop()
      //转base64
      this.loadImage()
    })
  }

  async crop() {
    let origin = await this.decodeImage(this.selectedUri)
    if (origin != undefined) {
      let info = await origin.getImageInfo()
      //根据自己要求填写尺寸
      let region: image.Region = { x: 0, y: 0, size: { height: info.size.height / 2, width: info.size.width } };
      origin.crop(region).then(async () => {
        if (origin != undefined) {
          let pixel = await copyPixelMap(origin);
          origin.release();
          this.cropped = pixel;
          console.info('Sucessed in setting crop.');
        }
      }).catch((err: BusinessError) => {
        console.error('Failed to crop pixelmap.');
      })
    }
  }

  //通过图片uri转为ArrayBuff
  async loadImage() {

    let f = await fileIo.open(this.selectedUri, fileIo.OpenMode.READ_ONLY);
    let photoSize = fileIo.statSync(f.fd).size;
    console.info('Photo Size: ' + photoSize);
    let buffer = new ArrayBuffer(photoSize);
    fileIo.readSync(f.fd, buffer);
    fileIo.closeSync(f);
    let base64 = new util.Base64Helper(); // 实例化Base64Helper
    let unit8data = base64.encodeSync(new Uint8Array(buffer.slice(0, buffer.byteLength))) // 转换成Uint8Array
    console.info(`data长度:${unit8data.length}`)
    let textDecoder = util.TextDecoder.create('utf-8', { ignoreBOM : true })
    let retStr = textDecoder.decodeWithStream( unit8data , {stream: false}); // 可以把Uint8Array转码成base64
    console.log('imageSource: ' + retStr);

  }


  build() {
    Column() {
      Button('选择图片')
        .onClick(async () => {
          this.selectPhoto()
        })
      Image(this.selectedUri)
        .width('100%')
        .height('100%')
        .layoutWeight(1)
        .objectFit(ImageFit.Contain)

      Image(this.cropped)
        .width('100%')
        .height('100%')
        .layoutWeight(1)
        .objectFit(ImageFit.Contain)
    }
    .width(`100%`)
  }
}

async function copyPixelMap(imagePixel: PixelMap): Promise<image.PixelMap> {
  let imageInfo: image.ImageInfo = await imagePixel.getImageInfo();
  console.info(`copyPixelMapSize: width:${imageInfo?.size.width} height:${imageInfo?.size.height}`);
  let newRegion: image.Region = {
    size: { height: imageInfo.size.height, width: imageInfo.size.width },
    x: 0,
    y: 0
  }
  let newArea: image.PositionArea = {
    pixels: new ArrayBuffer(imageInfo.size.height * imageInfo.size.width * 4),
    offset: 0,
    stride: imageInfo.stride,
    region: newRegion
  }
  await imagePixel.readPixels(newArea);
  let opts: image.InitializationOptions = { editable: true, pixelFormat: 4, size: imageInfo.size };
  let imagePixelCache = await image.createPixelMap(newArea.pixels, opts);
  return imagePixelCache;
}
分享
微博
QQ
微信
回复
3天前
相关问题
HarmonyOS 如何base64数据转换为图片
523浏览 • 1回复 待解决
HarmonyOS base64编码API
197浏览 • 1回复 待解决
HarmonyOS base64解码报错
1050浏览 • 1回复 待解决
HarmonyOS 图片Base64编码
59浏览 • 1回复 待解决
HarmonyOS base64编码问题
655浏览 • 1回复 待解决
HarmonyOS base64转image
61浏览 • 1回复 待解决
HarmonyOS 图片转base64
63浏览 • 1回复 待解决
HarmonyOS Image如何显示base64图片?
473浏览 • 1回复 待解决
验证pixelmap数据buffer转base64是否正常
1841浏览 • 1回复 待解决
HarmonyOS arraybuffer转base64乱码
165浏览 • 1回复 待解决
HarmonyOS string怎么base64和decodeBase64
57浏览 • 1回复 待解决
HarmonyOS如何将图片转Base64
918浏览 • 1回复 待解决
HarmonyOS 中文base64加密解密乱码
575浏览 • 1回复 待解决
HarmonyOS 图片进行base64编码报错
701浏览 • 1回复 待解决
如何base64转换成图片?
10329浏览 • 2回复 待解决
HarmonyOS SM2加签返回Base64字符串
37浏览 • 1回复 待解决