1# 如何请求并加载网络图片
2
3## 场景说明
4加载网络图片时,如果直接在Image组件中写入图片的url链接,当网速较慢或者图片较大时,可能导致Image组件加载不出图片。因此,建议使用http接口请求图片数据,等数据返回后通过状态变量实时将图片加载到页面上,这样就能保证图片的渲染。本例将为大家介绍如何实现上述场景。
5
6## 效果呈现
7本例效果如下:
8
9![httpforimage](figures/httpforimage.gif)
10
11## 运行环境
12- IDE:DevEco Studio 3.1 Beta1
13- SDK:Ohos_sdk_public 3.2.11.9 (API Version 9 Release)
14
15## 实现思路
16- 使用http请求获取图片数据。
17- 通过image.createImageSource()将获取到的数据转化为图片源实例。
18- 调用createPixelMap()将图片数据解析为pixelmap。
19- 将pixelmap通过状态变量传入Image组件进行渲染显示。
20
21## 开发步骤
221. 申请网络权限。
23使用http请求需要先申请网络权限,在module.json5文件中添加以下配置:
24    ```json
25    "requestPermissions":[
26      {
27        "name": "ohos.permission.INTERNET",
28      },
29    ]
30    ```
312. 构建UI框架。
32
33    ```ts
34    @Entry
35    @Component
36    struct NetPic {
37      // 先创建一个PixelMap状态变量用于接收网络图片数据
38      @State image: PixelMap = undefined
39      build() {
40        Column({ space: 10 }) {
41          Button("获取网络图片")
42            .onClick(() => {
43              this.httpRequest();
44            })
45          Image().height(100).width(100)
46        }
47        .width('100%')
48        .height('100%')
49        .padding(10)
50      }
51    }
52    ```
533. 先使用http请求获取图片数据,再通过image.createImageSource()将获取到的数据转化为图片源实例,然后调用createPixelMap()将图片数据解析为pixelmap。
54    ```ts
55    @Entry
56    @Component
57    struct NetPic {
58      // 先创建一个PixelMap状态变量用于接收网络图片
59      @State image: PixelMap = undefined
60      // 网络图片请求方法
61      httpRequest() {
62        let httpRequest = http.createHttp();
63        httpRequest.request(
64          //网络图片地址
65          "https://images.openharmony.cn/330-%E8%BF%90%E8%90%…%BE/%E6%B4%BB%E5%8A%A8/419/3.2releas-1920-480.jpg",
66          (error, data) => {
67            if (error) {
68              console.log("error code: " + error.code + ", msg: " + error.message)
69            } else {
70              let code = data.responseCode
71              if (ResponseCode.ResponseCode.OK == code) {
72                let res: any = data.result
73                //通过获取到的uri创建图片源实例。
74                let imageSource = image.createImageSource(res)
75                let options = {
76                  // 透明度
77                  alphaType: 0,
78                  // 是否可编辑
79                  editable: false,
80                  // 像素格式
81                  pixelFormat: 3,
82                  // 缩略值
83                  scaleMode: 1,
84                  // 创建图片大小
85                  size: { height: 100, width: 100 }
86                }
87                //将图片数据解析为pixelmap,并设置option属性。
88                imageSource.createPixelMap(options).then((pixelMap) => {
89                  // 将pixelmap通过状态变量image传递给Image组件,将图片信息加载出来。
90                  this.image = pixelMap
91                })
92              } else {
93                console.log("response code: " + code);
94              }
95            }
96          }
97        )
98      }
99      ...
100    }
101    ```
1024. 将状态变量image传递给Image组件,将图片加载出来。
103    ```ts
104    ...
105      build() {
106        Column({ space: 10 }) {
107          Button("获取网络图片")
108            .onClick(() => {
109              this.httpRequest();
110            })
111          // 将状态变量image传递给Image组件,当image获取到图片数据时,可以实时刷新UI
112          Image(this.image).height(100).width(100)
113        }
114        .width('100%')
115        .height('100%')
116        .padding(10)
117      }
118    ...
119    ```
120
121## 完整代码
122本例完整代码如下:
123```ts
124import http from '@ohos.net.http';
125import ResponseCode from '@ohos.net.http';
126import image from '@ohos.multimedia.image'
127
128@Entry
129@Component
130struct NetPic {
131  // 先创建一个PixelMap状态变量用于接收网络图片
132  @State image: PixelMap = undefined
133  // 网络图片请求方法
134  httpRequest() {
135    let httpRequest = http.createHttp();
136    httpRequest.request(
137      //网络图片地址
138      "https://images.openharmony.cn/330-%E8%BF%90%E8%90%…%BE/%E6%B4%BB%E5%8A%A8/419/3.2releas-1920-480.jpg",
139      (error, data) => {
140        if (error) {
141          console.log("error code: " + error.code + ", msg: " + error.message)
142        } else {
143          let code = data.responseCode
144          if (ResponseCode.ResponseCode.OK == code) {
145            let res: any = data.result
146            //通过获取到的uri创建图片源实例。
147            let imageSource = image.createImageSource(res)
148            let options = {
149              // 透明度
150              alphaType: 0,
151              // 是否可编辑
152              editable: false,
153              // 像素格式
154              pixelFormat: 3,
155              // 缩略值
156              scaleMode: 1,
157              // 创建图片大小
158              size: { height: 100, width: 100 }
159            }
160            //将图片数据解析为pixelmap,并设置option属性。
161            imageSource.createPixelMap(options).then((pixelMap) => {
162              // 将pixelmap通过状态变量image传递给Image组件,将图片信息加载出来。
163              this.image = pixelMap
164            })
165          } else {
166            console.log("response code: " + code);
167          }
168        }
169      }
170    )
171  }
172
173  build() {
174    Column({ space: 10 }) {
175      Button("获取网络图片")
176        .onClick(() => {
177          this.httpRequest();
178        })
179      // 将状态变量image传递给Image组件,当image获取到图片数据时,可以实时刷新UI
180      Image(this.image).height(100).width(100)
181    }
182    .width('100%')
183    .height('100%')
184    .padding(10)
185  }
186}
187```
188
189## 参考
190- [图片处理](../application-dev/reference/apis-image-kit/js-apis-image.md)
191
192- [数据请求](../application-dev/reference/apis-network-kit/js-apis-http.md)
193
194- [权限申请指导](../application-dev/security/AccessToken/declare-permissions.md)