【harmonyOS】如果有些图片url用Image组件加载不显示,可以request下载后利用PixelMap加载。

【HarmonyOS】鸿蒙图片下载加载方案_JSON

需要网络权限:src/main/module.json5

    "requestPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      },

src/main/ets/pages/Page010.ets

import { http } from '@kit.NetworkKit'
import { image } from '@kit.ImageKit'

@Entry
@Component
struct Page010 {
  @State pixelMap: PixelMap | undefined = undefined
  @State imgUrl: string = 'https://img0.baidu.com/it/u=3129379276,3231297819&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500'

  build() {
    Column() {

      Text('加载url显示')
      Image(this.imgUrl).width('200lpx').height('200lpx')
        .onError((error: ImageError) => {
          console.info('error', JSON.stringify(error))
        })
        .onComplete((event) => {
          console.info('event', JSON.stringify(event))
        })
      Button('下载图片').onClick(() => {
        http.createHttp().request(
          this.imgUrl,
          { expectDataType: http.HttpDataType.ARRAY_BUFFER }
        ).then(async (res) => {
          console.info('res', JSON.stringify(res))
          // 将图片资源转为像素图(PixelMap)
          this.pixelMap = await image.createImageSource(res.result as ArrayBuffer).createPixelMap()
        }).catch(() => {
          console.info('catch')
        })
      })
      Text('下载图片后显示')
      Image(this.pixelMap).width('200lpx')
    }
    .width('100%')
    .height('100%')
  }
}