【HarmonyOS】图片下载加载方案

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

cke_267.png

需要网络权限: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%')
  }
}
复制代码

 

posted @   zhongcx  阅读(26)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示