• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Displaying Images
2
3
4More often than not, you may need to display images in your application, for example, logos in buttons, online images, and local images. To do so, you need to use the **\<Image>** component, which supports a wide range of image formats, including PNG, JPG, BMP, SVG, and GIF. For details, see [Image](../reference/arkui-ts/ts-basic-components-image.md).
5
6
7You can call the API in the following format to create an image:
8
9
10
11```ts
12Image(src: string | Resource | media.PixelMap)
13```
14
15
16Obtains a local or online image from the image data source specified by **src**. For details about how to load the data source, see [Loading Image Resources](#loading-image-resources).
17
18
19## Loading Image Resources
20
21The **\<Image>** component supports two types of images: archived and pixel map.
22
23
24### Archived Type Data Source
25
26Data sources of the archived type can be classified into local resources, online resources, **Resource** objects, media library data share resources, and Base64 resources.
27
28- Local resources
29  Create a folder and place a local image in any position in the **ets** folder.
30
31  In the **\<Image>** component, import the local image path to display the image. The root directory is the **ets** folder.
32
33  ```ts
34  Image('images/view.jpg')
35  .width(200)
36  ```
37
38- Online resources
39  To use online images, first apply for the **ohos.permission.INTERNET** permission. For details, see [Applying for Permissions](../security/accesstoken-guidelines.md). Under this scenario, the **src** parameter of the **\<Image>** component is the URL of the online image.
40
41  ```ts
42  Image('https://www.example.com/example.JPG') // Replace the URL with the actual URL.
43  ```
44
45- **Resource** objects
46  **Resource** objects can be used to import images across bundles and modules. All images in the **resources** folder can be read and converted to the **Resource** objects through **$r**.
47
48  **Figure 1** resources folder
49
50  ![image-resource](figures/image-resource.jpg)
51
52  API:
53
54  ```
55  Image($r('app.media.icon'))
56  ```
57
58  You can also place the images in the **rawfile** folder.
59
60  **Figure 2** rawfile folder
61
62 ![image-rawfile](figures/image-rawfile.jpg)
63
64  API:
65
66  ```
67  Image($rawfile('snap'))
68  ```
69
70- Media library data share resources
71  To display images from the media library, use a path string that starts with **datashare://**.
72
73  1. Call the API to obtain the image URL in the media library.
7475      ```ts
76      import picker from '@ohos.file.picker';
77
78      @Entry
79      @Component
80      struct Index {
81        @State imgDatas: string[] = [];
82        // Obtain the image URL set.
83        getAllImg() {
84          let photoPicker = new picker.PhotoViewPicker();
85          let result = new Array<string>();
86          try {
87            let PhotoSelectOptions = new picker.PhotoSelectOptions();
88            PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
89            PhotoSelectOptions.maxSelectNumber = 5;
90            let photoPicker = new picker.PhotoViewPicker();
91            photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult) => {
92              this.imgDatas = PhotoSelectResult.photoUris;
93              console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult));
94            }).catch((err) => {
95              console.error(`PhotoViewPicker.select failed with. Code: ${err.code}, message: ${err.message}`);
96            });
97          } catch (err) {
98            console.error(`PhotoViewPicker failed with. Code: ${err.code}, message: ${err.message}`);    }
99        }
100
101        // Call the preceding function in aboutToAppear to obtain the URLs of all images in the gallery and store the URLs in imgDatas.
102        async aboutToAppear() {
103          this.getAllImg();
104        }
105        // Use the URL of imgDatas to load the image.
106        build() {
107          Column() {
108            Grid() {
109              ForEach(this.imgDatas, item => {
110                GridItem() {
111                  Image(item)
112                    .width(200)
113                }
114              }, item => JSON.stringify(item))
115            }
116          }.width('100%').height('100%')
117        }
118      }
119      ```
120  2. Check the format of the URL obtained from the media library is as follows:
121122      ```ts
123      Image('datashare:///media/5')
124      .width(200)
125      ```
126
127- base64
128
129  As shown above, the URL format is data:image/[png|jpeg|bmp|webp];base64,[base64 data], in which **[base64 data]** indicates Base64 string data.
130
131  Base64 strings are widely used on web pages for storing pixel data of images.
132
133
134### Pixel Map
135
136A pixel map is a pixel image obtained after image decoding. For details, see [Image Development](../media/image-overview.md). In the following example, the data returned by the loaded online image is decoded into a pixel map, which is then displayed on the **\<Image>** component.
137
1381. Create a **PixelMap** state variable.
139
140   ```ts
141   @State image: PixelMap = undefined;
142   ```
143
1442. Reference multimedia.
145   Request an online image and implement transcoding to generate a pixel map.
146
147   1. Reference the network access permission and media library permission.
148149       ```ts
150       import http from '@ohos.net.http';
151       import ResponseCode from '@ohos.net.http';
152       import image from '@ohos.multimedia.image';
153       ```
154   2. Enter the online image address.
155156       ```ts
157       http.createHttp().request("https://www.example.com/xxx.png",
158         (error, data) => {
159           if (error){
160             console.error(`http reqeust failed with. Code: ${error.code}, message: ${error.message}`);
161           } else {
162           }
163         }
164       )
165       ```
166   3. Transcode the data returned by the online image address to a pixel map.
167168       ```ts
169       let code = data.responseCode;
170       if(ResponseCode.ResponseCode.OK === code) {
171         let imageSource = image.createImageSource(data.result);
172         let options = {
173           alphaType: 0,                     // Alpha type.
174           editable: false,                  // Whether the image is editable.
175           pixelFormat: 3,                   // Pixel format.
176           scaleMode: 1,                     // Scale mode.
177           size: {height: 100, width: 100}
178          }  // Image size.
179           imageSource.createPixelMap(options).then((pixelMap) => {
180           this.image = pixelMap
181       })
182       ```
183   4. Display the image.
184185       ```ts
186       Button ("Get Online Image")
187         .onClick(() => {
188           this.httpRequest()
189         })
190       Image(this.image).height(100).width(100)
191       ```
192
193
194## Display the vector image.
195
196The **\<Image>** component can display vector images in SVG format. The supported SVG labels are **svg**, **rect**, **circle**, **ellipse**, **path**, **line**, **polyline**, **polygon**, and **animate**.
197
198You can use the **fillColor** attribute to change the fill color of an SVG image.
199
200
201```ts
202Image($r('app.media.cloud')).width(50)
203.fillColor(Color.Blue)
204```
205
206  **Figure 3** Original image
207
208![screenshot_20230223_141141](figures/screenshot_20230223_141141.png)
209
210  **Figure 4** SVG image after the fill color is set
211
212![screenshot_20230223_141404](figures/screenshot_20230223_141404.png)
213
214
215## Adding Attributes
216
217Setting attributes for the **\<Image>** component can spruce up the image with custom effects. The following are examples of common attributes. For details about all attributes, see [Image](../reference/arkui-ts/ts-basic-components-image.md).
218
219
220### Setting the Image Scale Mode
221
222The **objectFit** attribute is used to scale an image to fit it into a container whose height and width are determined.
223
224
225```ts
226@Entry
227@Component
228struct MyComponent {
229  scroller: Scroller = new Scroller()
230
231  build() {
232    Scroll(this.scroller) {
233      Row() {
234        Image($r('app.media.img_2')).width(200).height(150)
235          .border({ width: 1 })
236          .objectFit(ImageFit.Contain).margin(15) // The image is scaled with its aspect ratio retained to fit within the display boundaries.
237          .overlay('Contain', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
238        Image($r('app.media.ic_img_2')).width(200).height(150)
239          .border({ width: 1 })
240          .objectFit(ImageFit.Cover).margin(15)
241          // The image is scaled with its aspect ratio retained for both sides to be greater than or equal to the display boundaries.
242          .overlay('Cover', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
243        Image($r('app.media.img_2')).width(200).height(150)
244          .border({ width: 1 })
245            // The image is scaled automatically to fit the display area.
246          .objectFit(ImageFit.Auto).margin(15)
247          .overlay('Auto', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
248      }
249      Row() {
250        Image($r('app.media.img_2')).width(200).height(150)
251          .border({ width: 1 })
252          .objectFit(ImageFit.Fill).margin(15)
253          // The image is scaled to fill the display area, and its aspect ratio is not retained.
254          .overlay('Fill', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
255        Image($r('app.media.img_2')).width(200).height(150)
256          .border({ width: 1 })
257          // The image content is displayed with its aspect ratio retained. The size is smaller than or equal to the original size.
258          .objectFit(ImageFit.ScaleDown).margin(15)
259          .overlay('ScaleDown', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
260        Image($r('app.media.img_2')).width(200).height(150)
261          .border({ width: 1 })
262          // The original size is retained.
263          .objectFit(ImageFit.None).margin(15)
264          .overlay('None', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
265      }
266    }
267  }
268}
269```
270
271![en-us_image_0000001511421240](figures/en-us_image_0000001511421240.png)
272
273
274### Synchronously Loading Images
275
276Generally, the image loading process is performed asynchronously to avoid blocking the main thread and to streamline UI interaction. In certain cases, however, the image may flicker when refreshed. If this occurs, you can use the **syncLoad** attribute to load the image synchronously to avoid flickering. You are not advised to use this attribute when the image loading takes a long time. Otherwise, the page may fail to respond.
277
278
279```ts
280Image($r('app.media.icon'))
281  .syncLoad(true)
282```
283
284
285## Adding Events
286
287By binding the **onComplete** event to the **\<Image>** component, you can obtain necessary information about the image after the image is successfully loaded. You can also bind the **onError** event to obtain error information when the image fails to be loaded.
288
289
290```ts
291@Entry
292@Component
293struct MyComponent {
294  @State widthValue: number = 0
295  @State heightValue: number = 0
296  @State componentWidth: number = 0
297  @State componentHeight: number = 0
298
299  build() {
300    Column() {
301      Row() {
302        Image($r('app.media.ic_img_2'))
303          .width(200)
304          .height(150)
305          .margin(15)
306          .onComplete((msg: {
307            width: number,
308            height: number,
309            componentWidth: number,
310            componentHeight: number
311          }) => {
312            this.widthValue = msg.width
313            this.heightValue = msg.height
314            this.componentWidth = msg.componentWidth
315            this.componentHeight = msg.componentHeight
316          })
317            // If the image fails to be obtained, print the result.
318          .onError(() => {
319            console.info('load image fail')
320          })
321          .overlay('\nwidth: ' + String(this.widthValue) + ', height: ' + String(this.heightValue) + '\ncomponentWidth: ' + String(this.componentWidth) + '\ncomponentHeight: ' + String(this.componentHeight), {
322            align: Alignment.Bottom,
323            offset: { x: 0, y: 60 }
324          })
325      }
326    }
327  }
328}
329```
330
331
332![en-us_image_0000001511740460](figures/en-us_image_0000001511740460.png)
333