• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Image
2
3The **\<Image>** component is usually used to display images in applications. It supports images in PNG, JPG, BMP, SVG, or GIF format from the following data sources: [PixelMap](../apis/js-apis-image.md#pixelmap7), [ResourceStr](ts-types.md#resourcestr), or [DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor).
4
5> **NOTE**
6>
7> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
8
9
10## Required Permissions
11
12To use online images, the application must have the **ohos.permission.INTERNET** permission. For details about how to apply for a permission, see [Declaring Permissions](../../security/accesstoken-guidelines.md).
13
14
15## Child Components
16
17Not supported
18
19
20## APIs
21
22Image(src: PixelMap | ResourceStr | DrawableDescriptor)
23
24Obtains an image from the specified source for subsequent rendering and display.
25
26If the **\<Image>** component fails to obtain the image or the obtained image size is 0, the **\<Image>** component is automatically resized to 0 and does not follow the layout constraints of its parent component.
27
28Since API version 9, this API is supported in ArkTS widgets.
29
30**Parameters**
31
32| Name| Type                                                    | Mandatory| Description                                                    |
33| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
34| src    | [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [ResourceStr](ts-types.md#resourcestr) \| [DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor) | Yes  | Data source of the image. Local and online sources are supported. For details about how to reference an image, see [Loading Image Resources](../../ui/arkts-graphics-display.md#loading-image-resources).<br>1. **PixelMap**: an array of pixels storing graphical information. This type is usually used in image editing scenarios.<br>2. **ResourceStr**: a string or a **Resource** object.<br>The string format can be used to load local images and, more frequently, online images. When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **\<Image>** component cannot be called across bundles or modules. If an image needs to be used globally, you are advised to use the **Resource** format. The following types of strings are supported:<br>- Base64 strings in the format of data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where **[base64 data]** is a Base64 string.<br>- Strings with the **file://** prefix, which are used to access the images in the **files** folder in the installation directory of the application. Ensure that the application has the read permission to the files in the specified path.<br>The **Resource** format allows for access across bundles and modules. It is recommended for accessing local images.<br>3. **DrawableDescriptor**: an object created when the passed resource ID or name belongs to a common image.<br>**NOTE**<br>- ArkTS widgets support GIF animations, but the animations only play once on display.<br>- ArkTS widgets do not support the strings with the **http://** or **file://** prefix, or the [PixelMap](../apis/js-apis-image.md#pixelmap7) type.<br>- Online images must support the RFC 9113 standard to be successfully loaded.|
35
36## Attributes
37
38For details about how to use attributes, see [Setting Attributes](../../ui/arkts-graphics-display.md#setting-attributes). In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
39
40| Name                            | Type                                               | Description                                                        |
41| -------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------ |
42| alt                              | string \| [Resource](ts-types.md#resource)         | Placeholder image displayed during loading. Local images (in PNG, JPG, BMP, SVG, or GIF format) are supported. Online images are not supported.<br>Default value: **null**<br>Since API version 9, this API is supported in ArkTS widgets.|
43| objectFit                        | [ImageFit](ts-appendix-enums.md#imagefit)               | How the image is resized to fit its container.<br>Default value: **ImageFit.Cover**<br>Since API version 9, this API is supported in ArkTS widgets.|
44| objectRepeat                     | [ImageRepeat](ts-appendix-enums.md#imagerepeat)         | How the image is repeated. When set to repeat, the image is repeated from the center to edges. The last image will be clipped if it does not fit in the component.<br>Default value: **ImageRepeat.NoRepeat**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute is not applicable to SVG images.|
45| interpolation                    | [ImageInterpolation](#imageinterpolation)               | Interpolation effect of the image, which can alleviate aliasing that occurs when the image is zoomed.<br>Default value: **ImageInterpolation.None**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>When the image is zoomed out, high quality interpolation is not applicable. You are advised to use medium or low quality interpolation instead.<br>This attribute is not applicable to SVG images.|
46| renderMode                       | [ImageRenderMode](#imagerendermode)                     | Rendering mode of the image, which can be **Original** or **Template** (monochrome).<br>Default value: **ImageRenderMode.Original**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute is not applicable to SVG images.|
47| sourceSize                       | {<br>width: number,<br>height: number<br>} | Decoding size of the image. This attribute can be used to reduce the image resolution when the image display size needs to be smaller than the component size. When used together with **ImageFit.None**, it can display a small image in the component.<br>Unit: px<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute works only when the target size is smaller than the source size.<br>This attribute is not applicable to SVG images.<br>This attribute is not applicable to **PixelMap** objects.|
48| matchTextDirection               | boolean                                                 | Whether to display the image in the system language direction. When this parameter is set to true, the image is horizontally flipped in the right-to-left (RTL) language context.<br>Default value: **false**<br>Since API version 9, this API is supported in ArkTS widgets.|
49| fitOriginalSize                  | boolean                                                 | Whether to fit the component to the original size of the image source when the component size is not set.<br>Default value: **false**<br>Since API version 9, this API is supported in ArkTS widgets.|
50| fillColor                        | [ResourceColor](ts-types.md#resourcecolor)              | Fill color to be superimposed on the image.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute applies only to an SVG image. Once set, the fill color will replace that of the SVG image.|
51| autoResize                       | boolean                                                 | Whether to resize the image source based on the size of the display area during image decoding. This resizing can help reduce the memory usage. For example, if the size of the original image is 1920 x 1080 and the size of the display area is 200 x 200, you can set this attribute to **true** so that the image is downsampled to 200 x 200.<br>Default value: **true**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>As downsampling images results in some loss of information, it may reduce the image quality, causing issues such as aliasing. To retain the original image quality, set **autoResize** to **false**.|
52| syncLoad<sup>8+</sup>            | boolean                                                 | Whether to load the image synchronously. By default, the image is loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder image is not displayed.<br>Default value: **false**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>When loading a small image, you are advised to set **syncLoad** to **true** so that the image loading can be quickly completed on the main thread.|
53| copyOption<sup>9+</sup>          | [CopyOptions](ts-appendix-enums.md#copyoptions9)        | Whether the image can be copied.<br>When **copyOption** is set to a value other than **CopyOptions.None**, the image can be copied in various manners, such as long pressing, right-clicking, or pressing Ctrl+C.<br>Default value: **CopyOptions.None**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>SVG images cannot be copied.|
54| colorFilter<sup>9+</sup>         | [ColorFilter](ts-types.md#colorfilter9)                 | Color filter of the image. The input parameter is a 4 x 5 RGBA transformation matrix.<br>The first row of the matrix represents a vector value of R (red), the second row represents a vector value of G (green), the third row represents a vector value of B (blue), and the fourth row represents a vector value of A (alpha). The four rows represent different RGBA vector values.<br>The RGBA values are floating-point numbers between 0 and 1. When the diagonal value of the matrix is 1, the original color of the image is retained.<br> **Calculation rule:**<br>If the input filter matrix is as follows:<br>![image-matrix-1](figures/image-matrix-1.jpg)<br>Wherein the color is [R, G, B, A].<br>Then the color after filtering is [R', G', B', A'].<br>![image-matrix-2](figures/image-matrix-2.jpg)<br>Since API version 9, this API is supported in ArkTS widgets.|
55| draggable| boolean                                                 | Whether the image is draggable. The value **true** means that the image is draggable, and **false** means the opposite.<br>This attribute cannot be used together with the [onDragStart](ts-universal-events-drag-drop.md) event.<br>Default value: **false**<br>**NOTE**<br>This API is supported since API version 9.|
56
57>  **NOTE**
58>
59>  - To use shortcut keys to copy the **\<Image>** component, the component must be [in focus](../../ui/arkts-common-events-focus-event.md#setting-whether-a-component-is-focusable). By default, the **\<Image>** component is not focusable. To enable it to gain focus, set both the [focusable](ts-universal-attributes-focus.md) and [focusOnTouch](ts-universal-attributes-focus.md) attributes to **true**.
60>  - For SVG images, only the following tags are included in the supported list: **svg**, **rect**, **circle**, **ellipse**, **path**, **line**, **polyline**, and **polygon**.
61
62## ImageInterpolation
63
64Since API version 9, this API is supported in ArkTS widgets.
65
66| Name  | Description                                                |
67| ------ | ---------------------------------------------------- |
68| None   | No image interpolation.                                    |
69| High   | High quality interpolation. This mode produces scaled images of the highest possible quality, but may require more image rendering time.|
70| Medium | Medium quality interpolation.                                        |
71| Low    | Low quality interpolation.                                        |
72
73## ImageRenderMode
74
75Since API version 9, this API is supported in ArkTS widgets.
76
77| Name    | Description          |
78| -------- | -------------- |
79| Original | Render image pixels as they are in the original source image.|
80| Template | Render image pixels to create a monochrome template image.|
81
82## Events
83
84In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
85
86### onComplete
87
88onComplete(callback: (event?: { width: number, height: number, componentWidth: number, componentHeight: number, loadingStatus: number,contentWidth: number, contentHeight: number, contentOffsetX: number, contentOffsetY: number}) =&gt; void) }) =&gt; void)
89
90Triggered when an image is successfully loaded or decoded. The size of the loaded image is returned.
91
92Since API version 9, this API is supported in ArkTS widgets.
93
94**Parameters**
95
96| Name                      | Type  | Description                                                        |
97| ---------------------------- | ------ | ------------------------------------------------------------ |
98| width                        | number | Width of the image.<br>Unit: pixel                                   |
99| height                       | number | Height of the image.<br>Unit: pixel                                   |
100| componentWidth               | number | Width of the component.<br>Unit: pixel                                   |
101| componentHeight              | number | Height of the component.<br>Unit: pixel                                   |
102| loadingStatus                | number | Loading status of the image.<br>**NOTE**<br>If the return value is **0**, the image is successfully loaded. If the return value is **1**, the image is successfully decoded.|
103| contentWidth<sup>10+</sup>   | number | Actual rendered width of the image.<br>Unit: pixel<br>**NOTE**<br>This parameter is valid only when the return value of **loadingStatus** is **1**.|
104| contentHeight<sup>10+</sup>  | number | Actual rendered height of the image.<br>Unit: pixel<br>**NOTE**<br>This parameter is valid only when the return value of **loadingStatus** is **1**.|
105| contentOffsetX<sup>10+</sup> | number | Offset of the rendered content relative to the component on the x-axis.<br>Unit: pixel<br>**NOTE**<br>This parameter is valid only when the return value of **loadingStatus** is **1**.|
106| contentOffsetY<sup>10+</sup> | number | Offset of the rendered content relative to the component on the y-axis<br>Unit: pixel<br>**NOTE**<br>This parameter is valid only when the return value of **loadingStatus** is **1**.|
107
108
109### onError
110
111onError(callback: (event?: { componentWidth: number, componentHeight: number , message: string }) =&gt; void)
112
113Triggered when an error occurs during image loading.
114
115Since API version 9, this API is supported in ArkTS widgets.
116
117**Parameters**
118
119| Name              | Type  | Description                     |
120| -------------------- | ------ | ------------------------- |
121| componentWidth       | number | Width of the component.<br>Unit: pixel|
122| componentHeight      | number | Height of the component.<br>Unit: pixel|
123| message<sup>9+</sup> | string | Error information.               |
124
125
126### onFinish
127
128onFinish(event: () =&gt; void)
129
130Triggered when the animation playback in the loaded SVG image is complete. If the animation is an infinite loop, this callback is not triggered.
131
132Only SVG images are supported.
133
134Since API version 9, this API is supported in ArkTS widgets.
135
136## Example
137
138### Loading Images of Basic Types
139
140
141```ts
142@Entry
143@Component
144struct ImageExample1 {
145  build() {
146    Column() {
147      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
148        Row() {
149          // Load a PNG image.
150          Image($r('app.media.ic_camera_master_ai_leaf'))
151            .width(110).height(110).margin(15)
152            .overlay('png', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
153          // Load a GIF image.
154          Image($r('app.media.loading'))
155            .width(110).height(110).margin(15)
156            .overlay('gif', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
157        }
158        Row() {
159          // Load an SVG image.
160          Image($r('app.media.ic_camera_master_ai_clouded'))
161            .width(110).height(110).margin(15)
162            .overlay('svg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
163          // Load a JPG image.
164          Image($r('app.media.ic_public_favor_filled'))
165            .width(110).height(110).margin(15)
166            .overlay('jpg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
167        }
168      }
169    }.height(320).width(360).padding({ right: 10, top: 10 })
170  }
171}
172```
173
174![en-us_image_0000001592882500](figures/en-us_image_0000001592882500.gif)
175
176### Loading Online Images
177
178The default network timeout period is 5 minutes for loading online images. When using an online image, you are advised to use **alt** to configure the placeholder image displayed during loading. If more flexible network configuration is required, you can use the [HTTP](../../connectivity/http-request.md) tool to send a network request, and then decode the returned data into a **PixelMap** object in the **\<Image>** component. For details about image development, see [Image Processing](../../media/image-overview.md).
179
180To use online images, the application must have the **ohos.permission.INTERNET** permission. For details about how to apply for a permission, see [Declaring Permissions](../../security/accesstoken-guidelines.md).
181
182```ts
183@Entry
184@Component
185struct ImageExample2 {
186  build() {
187    Column({ space: 10 }) {
188      Image("https://www.example.com/xxx.png")// Enter an image URL.
189        .alt($r('app.media.icon'))// Use alt to set a placeholder image displayed during image loading.
190        .width(100)
191        .height(100)
192    }
193  }
194}
195```
196
197
198### Adding Events to an Image
199
200
201```ts
202class tmp{
203  width: number = 0
204  height: number = 0
205}
206let msg:tmp = new tmp()
207@Entry
208@Component
209struct ImageExample3 {
210  @State widthValue: number = 0;
211  @State heightValue: number = 0;
212  private on: Resource = $r('app.media.image_on');
213  private off: Resource = $r('app.media.image_off');
214  private on2off: Resource = $r('app.media.image_on2off');
215  private off2on: Resource = $r('app.media.image_off2on');
216  @State src: Resource = this.on;
217
218  build() {
219    Column() {
220      Row({ space: 20 }) {
221        Column() {
222          Image($r('app.media.img_example1'))
223            .alt($r('app.media.ic_public_picture'))
224            .sourceSize({
225              width: 900,
226              height: 900
227            })
228            .objectFit(ImageFit.Cover)
229            .height(180).width(180)
230            // Obtain the size of an image after the image loading is complete.
231            .onComplete(msg => {
232              if(msg){
233                this.widthValue = msg.width
234                this.heightValue = msg.height
235              }
236            })
237            .onError(() => {
238              console.log('load image fail')
239            })
240            .overlay('\nwidth: ' + String(this.widthValue) + ' height: ' + String(this.heightValue), {
241              align: Alignment.Bottom,
242              offset: { x: 0, y: 20 }
243            })
244        }
245        // Add a click event so that a specific image is loaded upon clicking.
246        Image(this.src)
247          .width(120).height(120)
248          .onClick(() => {
249            if (this.src == this.on || this.src == this.off2on) {
250              this.src = this.on2off
251            } else {
252              this.src = this.off2on
253            }
254          })
255          .onFinish(() => {
256            if (this.src == this.off2on) {
257              this.src = this.on
258            } else {
259              this.src = this.off
260            }
261          })
262      }
263    }.width('100%')
264  }
265}
266```
267
268![en-us_image_0000001607845173](figures/en-us_image_0000001607845173.gif)
269