ITPub博客

首页 > 移动开发 > ANDROID > 【HarmonyOS】鸿蒙图片下载加载方案

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

原创 ANDROID 作者:afiua 时间:2024-09-26 11:31:02 0 删除 编辑

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


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

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


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%' )   } }


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/24984661/viewspace-3107416/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2011-12-13

  • 博文量
    20
  • 访问量
    56757