文档管理中心
FAQ媒体开发拍照和图片图片处理(Image)网络图片加载的两种方式及常见问题

网络图片加载的两种方式及常见问题

问题现象

在开发过程中会遇到很多加载网络图片的场景,例如使用Web组件加载网络图片,使用Image组件加载网络图片。本文详细介绍了如何使用这两个组件加载网络图片以及两个组件的区别和适用场景。

背景知识

开发过程中,加载网络图片可以使用Web组件和Image组件。Web组件具有网页显示的能力,进行图片加载可以直接加载在线地址;Image为图片组件,常用于在应用中显示图片。

展开

组件

适用类型

Web

图片在线地址。

Image

支持加载PixelMap、ResourceStr和DrawableDescriptor类型的数据源,支持png、jpg、jpeg、bmp、svg、webp、gif和heif类型的图片格式。

解决方案

  • 方案一:使用Web组件进行图片加载。
    使用Web组件加载网络图片资源时,需添加网络权限:ohos.permission.INTERNET,具体申请方式请参考声明权限。使用Web组件加载网络图片,可以直接加载图片的在线地址或者带后缀名的图片地址,其具备两个属性:onlineImageAccessimageAccess,onlineImageAccess设置是否允许从网络加载图片资源(通过HTTP和HTTPS访问的资源),默认允许访问,默认值:true;imageAccess设置是否允许自动加载图片资源,默认允许,默认值:true。代码示例如下:
    收起
    自动换行
    深色代码主题
    复制
    1. Web({ src: $rawfile('index.html'), controller: this.controller })
    2. .height(200)
    3. .javaScriptAccess(true)
    4. .onlineImageAccess(true)
    5. .imageAccess(true)
    6. .fileAccess(true)
    7. .geolocationAccess(false)
    8. .domStorageAccess(true);
  • 方案二:使用Image组件加载网络图片。
    使用Image组件加载网络图片时,默认网络超时是5分钟,在加载网络图片的过程中,建议使用alt配置加载时的占位图,使用HTTP工具包发送网络请求,然后将返回的数据解码为Image组件中的PixelMap,图片开发可参考图片处理。使用Image加载网络图片时,需要申请权限ohos.permission.INTERNET,具体申请方式请参考声明权限
    • 直接使用Image组件通过网络地址加载网络图片,代码示例如下:
      收起
      自动换行
      深色代码主题
      复制
      1. Image(this.url)
      2. .height(150)
      3. .objectFit(ImageFit.Auto)
      4. .onError((err: ImageError) => {
      5. // 图片无法加载时触发
      6. console.error(`Failed to do sth. Code: ${err.error?.code}, message: ${err.message}`);
      7. })
      8. .alt($r('app.media.startIcon'));
    • 使用Image加载PixelMap解码后的多媒体像素图。
      当开发者遇到需要对图片编辑或预览,或者动态生成的图片内容,或实时视频流帧捕捉与展示等情况时,可以使用PixelMap解码图片,然后使用Image进行加载。以下示例将加载的网络图片返回的数据解码成PixelMap格式,再显示在Image组件上。
      1. 创建PixelMap状态变量。
      2. 引用网络权限与媒体库权限,并填写网络图片地址,获取图片的二进制数据,代码示例如下:
        收起
        自动换行
        深色代码主题
        复制
        1. // 通过http的request方法从网络下载图片资源
        2. async getPicture() {
        3. http.createHttp()
        4. .request(this.url, (error: BusinessError, data: http.HttpResponse) => {
        5. if (error) {
        6. // 下载失败时弹窗提示检查网络,不执行后续逻辑
        7. console.error(`request failed, ${JSON.stringify(error.message)}`);
        8. return;
        9. }
        10. this.transcodePixelMap(data);
        11. });
        12. }
      3. 将网络地址成功返回的数据,编码转码成PixelMap的图片格式,参考链接:多媒体像素图。代码示例如下:
        收起
        自动换行
        深色代码主题
        复制
        1. /**
        2. * 使用createPixelMap将ArrayBuffer类型的图片转换为PixelMap类型
        3. * @param data:网络获取到的资源
        4. */
        5. transcodePixelMap(data: http.HttpResponse) {
        6. if (http.ResponseCode.OK === data.responseCode) {
        7. const imageData: ArrayBuffer = data.result as ArrayBuffer;
        8. // 通过ArrayBuffer创建图片源实例
        9. const imageSource: image.ImageSource = image.createImageSource(imageData);
        10. let imageInfo = imageSource.getImageInfoSync(0);
        11. let imgWidth = imageInfo.size.width;
        12. let imgHeight = imageInfo.size.height;
        13. const options: image.DecodingOptions = {
        14. 'editable': false,
        15. 'desiredSize': { width: imgWidth, height: imgHeight }
        16. };
        17. // 通过属性创建PixelMap
        18. imageSource.createPixelMap(options).then((pixelMap: PixelMap) => {
        19. this.image = pixelMap;
        20. });
        21. }
        22. }
      4. 使用Image组件进行图片加载。代码示例如下:
        收起
        自动换行
        深色代码主题
        复制
        1. Image(this.image!)
        2. .width('100%')
        3. .objectFit(ImageFit.Auto);

完整代码如下:

  • ArkTS侧:
    收起
    自动换行
    深色代码主题
    复制
    1. import { webview } from '@kit.ArkWeb';
    2. import { http } from '@kit.NetworkKit';
    3. import { image } from '@kit.ImageKit';
    4. import { BusinessError } from '@kit.BasicServicesKit';
    5. @Entry
    6. @Component
    7. struct Index {
    8. controller: WebviewController = new webview.WebviewController();
    9. uiContext: UIContext = this.getUIContext();
    10. @State image: PixelMap | null = null;
    11. url: string =
    12. encodeURI(''); // 网络图片链接url
    13. aboutToAppear() {
    14. this.getPicture();
    15. webview.WebviewController.setWebDebuggingAccess(true);
    16. }
    17. // 通过http的request方法从网络下载图片资源
    18. async getPicture() {
    19. http.createHttp()
    20. .request(this.url, (error: BusinessError, data: http.HttpResponse) => {
    21. if (error) {
    22. // 下载失败时弹窗提示检查网络,不执行后续逻辑
    23. console.error(`request failed, ${JSON.stringify(error.message)}`);
    24. return;
    25. }
    26. this.transcodePixelMap(data);
    27. });
    28. }
    29. /**
    30. * 使用createPixelMap将ArrayBuffer类型的图片转换为PixelMap类型
    31. * @param data:网络获取到的资源
    32. */
    33. transcodePixelMap(data: http.HttpResponse) {
    34. if (http.ResponseCode.OK === data.responseCode) {
    35. const imageData: ArrayBuffer = data.result as ArrayBuffer;
    36. // 通过ArrayBuffer创建图片源实例
    37. const imageSource: image.ImageSource = image.createImageSource(imageData);
    38. let imageInfo = imageSource.getImageInfoSync(0);
    39. let imgWidth = imageInfo.size.width;
    40. let imgHeight = imageInfo.size.height;
    41. const options: image.DecodingOptions = {
    42. 'editable': false,
    43. 'desiredSize': { width: imgWidth, height: imgHeight }
    44. };
    45. // 通过属性创建PixelMap
    46. imageSource.createPixelMap(options).then((pixelMap: PixelMap) => {
    47. this.image = pixelMap;
    48. });
    49. }
    50. }
    51. build() {
    52. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
    53. // 方案一:使用Web组件进行图片加载
    54. Web({ src: $rawfile('index.html'), controller: this.controller })
    55. .height(200)
    56. .javaScriptAccess(true)
    57. .onlineImageAccess(true)
    58. .imageAccess(true)
    59. .fileAccess(true)
    60. .geolocationAccess(false)
    61. .domStorageAccess(true);
    62. // 方案二:使用Image组件加载网络图片
    63. // 直接加载
    64. Image(this.url)
    65. .height(150)
    66. .objectFit(ImageFit.Auto)
    67. .onError((err: ImageError) => {
    68. // 图片无法加载时触发
    69. console.error(`Failed to do sth. Code: ${err.error?.code}, message: ${err.message}`);
    70. })
    71. .alt($r('app.media.startIcon'));
    72. // 解码后加载
    73. Image(this.image!)
    74. .width('100%')
    75. .objectFit(ImageFit.Auto);
    76. }
    77. .height('100%')
    78. .width('100%');
    79. }
    80. }
  • H5侧:
    收起
    自动换行
    深色代码主题
    复制
    1. <!-- main/resources/resfile/index.html -->
    2. <!DOCTYPE html>
    3. <html lang="en">
    4. <head>
    5. <meta charset="utf-8">
    6. <title>Demo</title>
    7. <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, viewport-fit=cover">
    8. <script>
    9. </script>
    10. </head>
    11. <body>
    12. <div class="page">
    13. <!-- 网络图片链接url -->
    14. <img src="" width="250" height="auto">
    15. </div>
    16. </body>
    17. </html>

常见FAQ

Q:使用Web组件进行图片加载和使用Image组件进行图片加载有什么区别?

A:使用Web组件和Image组件都支持加载本地图片和网络图片,但对于PixelMap类型图片Image组件可以直接加载,Web组件需要将PixelMap转化为base64字符串,或将其保存为本地图片并获取本地图片路径后用于加载。

Q:需要加载的图片文件名或路径中含有空格、特殊字符或者用户在填写表单时输入了一个带有空格的图片链接,或者某个API返回的图片地址中包含了未经编码的特殊字符,如何使用Image组件进行加载?

A:可以使用encodeURI编码对包含空格或特殊字符的图片地址进行编码,将这些字符替换为对应的编码形式,然后使用Image组件加载。代码示例如下:

收起
自动换行
深色代码主题
复制
  1. encodeURI(''); // 网络图片链接url

Q:使用Image组件加载图片时,图片无法加载,如何检测图片加载失败的原因。

A:检查网络连接和网络权限配置,并在Image组件下添加监听代码,监听图片加载失败原因代码示例如下:

收起
自动换行
深色代码主题
复制
  1. .onError((err: ImageError) => {
  2. // 图片无法加载时触发
  3. console.error(`Failed to do sth. Code: ${err.error?.code}, message: ${err.message}`);
  4. })

Q:在请求网络图片的过程中,如何进行证书校验?

A:使用Global.getContext中的filesDir方法获取应用沙箱路径,将图片下载至沙箱路径下,再用Image加载图片。

Q:使用Web组件如何加载HTTPS链接中的HTTP图片?

A:将Web组件的mixedMode属性设置为MixedMode.All来允许加载HTTP和HTTPS混合内容。

在 FAQ 中进行搜索
请输入您想要搜索的关键词