HarmonyOS 获取网络图片PixelMap?

image.createImageSource(uri: String)方法不支持网络图片url,那有没有办法获取网络图片的PixelMap信息,难道只能下载下来么。我这边可以通过ImageBitmap加载url后绘制到CanvasRenderer上面后再获取Canvas上面的PiexelMap数据,但是太麻烦了

阅读 477
1 个回答

只能下载,请参考示例如下:

import http from '@ohos.net.http';
import image from '@ohos.multimedia.image';
import { BusinessError } from '@ohos.base';

@Entry
@Component
struct ImageToPixelMap {
  @State image: PixelMap | undefined = undefined;

  httpRequest() {
    http.createHttp()
      .request("https://xxx.jpg",(error: BusinessError, data: http.HttpResponse) => {
        if (error) {
          console.error(`http reqeust failed with. Code: ${error.code}, message: ${error.message}`);
        } else {
          console.error('http reqeust success.');
          let imageData: ArrayBuffer = data.result as ArrayBuffer;
          let imageSource: image.ImageSource = image.createImageSource(imageData);
          console.error(`http reqeust size = ${imageData.byteLength}`);

          class tmp {
            height: number = 100;
            width: number = 100
          }

          let options: Record<string, number | boolean | tmp> = {
            'alphaType': 0, // 透明度
            'editable': false, // 是否可编辑
            'pixelFormat': 3, // 像素格式
            'scaleMode': 1, // 缩略值
            'size': { height: 100, width: 100 }
          } // 创建图片大小
          imageSource.createPixelMap(options).then((pixelMap: PixelMap) => {
            this.image = pixelMap
          })
        }
      })
  }

  build() {
    Column() {
      Button("获取网络图片")
        .onClick(() => {
          this.httpRequest()
        })
      Image(this.image).height(200).width(200)
    }.width('100%').height('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进