HarmonyOS 如何读取本地图片的实际长宽?

通过image.createPixelMap创建PixelMap对象,但是这个方法的参数InitializationOptions必须指定需要的长宽,但是我的目标就是获取长宽,这种方案似乎不可行。还有别的方式获得图片长宽吗

阅读 688
1 个回答

createImageSource并没有必须设置长宽,用的是 image.DecodingOptions;然后通过getImageInfo()获取

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

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  @State _pixelMap: image.PixelMap | undefined = undefined;
  @State with: number = 0
  @State hig: number = 0

  async aboutToAppear() {
    console.error("tag aboutToAppear start.");
    let resourceManager = getContext(this).resourceManager;
    let imageArray = await resourceManager.getMediaContent($r('app.media.startIcon'));
    let imageResource = image.createImageSource(imageArray.buffer);
    let opts: image.DecodingOptions = { editable: true }
    this._pixelMap = await imageResource.createPixelMap(opts);
    this._pixelMap.getImageInfo().then((imageInfo : image.ImageInfo) => {
      if (imageInfo == undefined) {
        console.error("Failed to obtain the image pixel map information.");
      }
      this.with = imageInfo.size.width;
      this.hig = imageInfo.size.height;
      console.log("Succeeded in obtaining the image pixel map information.", this.with, this.hig);
    })
    console.error("aboutToAppear end.");
  }

  build() {
    Column() {
      Image($r('app.media.startIcon'))
        .objectFit(ImageFit.None)
        .backgroundColor(Color.Green)
        .borderWidth(2)
        .width(this.with) //设置满足图片需求的宽高
        .height(this.hig)
    }
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进