• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2025 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import { http } from '@kit.NetworkKit';
17import { BusinessError } from '@kit.BasicServicesKit';
18import { image } from '@kit.ImageKit';
19
20/**
21 * 下载与显示网络图片
22 */
23@Entry
24@Component
25struct ImageExample002 {
26  @State pixelMapImg: PixelMap | undefined = undefined;
27
28  aboutToAppear() {
29    this.requestImageUrl('https://xxx/xxx.png');// 请填写一个具体的网络图片地址
30  }
31
32  requestImageUrl(url: string) {
33    http.createHttp().request(url, (error: BusinessError, data: http.HttpResponse)=> {
34      if (error) {
35        console.error(`request image failed: url: ${url}, code: ${error.code}, message: ${error.message}`);
36      } else {
37        let imgData: ArrayBuffer = data.result as ArrayBuffer;
38        console.info(`request image success, size: ${imgData.byteLength}`);
39        let imgSource: image.ImageSource = image.createImageSource(imgData);
40        class SizeTmp {
41          public height: number = 100
42          public width: number = 100
43        }
44        let options: Record<string, number | boolean | SizeTmp> = {
45          'alphaType': 0,
46          'editable': false,
47          'pixelFormat': 3,
48          'scaleMode': 1,
49          'size': { height: 100, width: 100 }
50        }
51        imgSource.createPixelMap(options).then((pixelMap: PixelMap) => {
52          console.error('image createPixelMap success');
53          this.pixelMapImg = pixelMap;
54        })
55      }
56    })
57  }
58
59  build() {
60    Column() {
61      Image(this.pixelMapImg)
62        .alt($r('app.media.img'))
63        .objectFit(ImageFit.None)
64        .width('100%')
65        .height('100%')
66    }
67  }
68}
69