• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Image
2
3The **Image** component is usually used to display images in applications. It supports data sources of the following types: [PixelMap](../../apis-image-kit/arkts-apis-image-PixelMap.md), [ResourceStr](ts-types.md#resourcestr), and [DrawableDescriptor](#drawabledescriptor10). Supported image formats include PNG, JPG, JPEG, BMP, SVG, WEBP, GIF, and HEIF. Note that the APNG and SVGA formats are not supported.
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> 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#focusable) and [focusOnTouch](ts-universal-attributes-focus.md#focusontouch9) attributes to **true**.
10>
11> The **Image** component supports SVG image sources. For details about SVG tags, see [SVG Tags](./ts-basic-svg.md).
12>
13> For animated images, animation playback is disabled by default and depends on the visibility of the **Image** component. When the component is visible, the animation is started through the callback. When the component is invisible, the animation is stopped. The visibility status of the **Image** component can be identified through the [onVisibleAreaChange](./ts-universal-component-visible-area-change-event.md#onvisibleareachange) event. If the value of **ratios** is greater than 0, the component is visible.
14>
15>For details about how to resolve white block issues during image loading, see [Solution to White Image Blocks](https://developer.huawei.com/consumer/en/doc/best-practices/bpta-image-white-lump-solution). For details about how to address slow image loading, see [Optimizing Preset Image Loading](https://developer.huawei.com/consumer/en/doc/best-practices/bpta-texture-compression-improve-performance).
16
17## Required Permissions
18
19The **ohos.permission.INTERNET** permission is required for using online images. For details about how to apply for a permission, see [Declaring Permissions](../../../security/AccessToken/declare-permissions.md).
20
21
22## Child Components
23
24Not supported
25
26
27## APIs
28
29### Image
30
31Image(src: PixelMap | ResourceStr | DrawableDescriptor)
32
33Obtains an image from the specified source for subsequent rendering and display.
34
35If 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.
36
37By default, the **Image** component crops images to keep their center. For example, if the component has the same width and height, it crops any image whose width and height are different, so as to keep its center.
38
39If the **Image** component does not have its width and height set, its size adapts to that of its parent component once the image is successfully loaded.
40
41**Widget capability**: This API can be used in ArkTS widgets since API version 9.
42
43**Atomic service API**: This API can be used in atomic services since API version 11.
44
45**System capability**: SystemCapability.ArkUI.ArkUI.Full
46
47**Parameters**
48
49| Name | Type                                    | Mandatory  | Description                                    |
50| ---- | ---------------------------------------- | ---- | ---------------------------------------- |
51| src  | [PixelMap](../../apis-image-kit/arkts-apis-image-PixelMap.md) \| [ResourceStr](ts-types.md#resourcestr)\| [DrawableDescriptor](#drawabledescriptor10) | 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 type 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<br>- Strings with the **file://** prefix, that is, [application sandbox URIs](../../apis-core-file-kit/js-apis-file-fileuri.md#constructor10): **file://\<bundleName>/\<sandboxPath>**, When accessing a path that contains special characters, use [fileUri.getUriFromPath(path)](../../apis-core-file-kit/js-apis-file-fileuri.md#fileurigeturifrompath) to transform the path into a URI that can handle special symbols. In addition, 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. If the [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12) type is passed in, the PixelMap array animation can be played.<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.|
52
53>**NOTE**
54>
55> Passing a URL directly to an **Image** component may lead to potential performance issues, such as: (1) Large images cannot be downloaded in advance during loading, resulting in a long display time of white blocks; (2) Small images set to load synchronously may block the UI thread in a weak network environment, causing screen freezes; (3) In a rapidly scrolling waterfall flow, images that are about to be displayed cannot be downloaded in advance, resulting in many white blocks during scrolling. Performance issues may manifest differently in different scenarios. To minimize these issues, separate the network download part from the display of the **Image** component, and download in advance or asynchronously. For details about how to resolve white block issues during image loading, see [Solution to White Image Blocks](https://developer.huawei.com/consumer/en/doc/best-practices/bpta-image-white-lump-solution). For details about how to address slow image loading, see [Optimizing Preset Image Loading](https://developer.huawei.com/consumer/en/doc/best-practices/bpta-texture-compression-improve-performance).
56>
57> When **src** is switched from a valid value (an image resource that can be parsed and loaded correctly) to an invalid value (an image path that cannot be parsed or loaded), the component should retain the previously successfully loaded image content without clearing or resetting it.
58>
59> If the input parameter is of the [PixelMap](../../apis-image-kit/arkts-apis-image-PixelMap.md) type, the **Image** component can detect data changes only when the reference to the **PixelMap** object is updated to point to a new instance. If modifications are made to the content of the **PixelMap** object, such as pixel values, but the reference to the object remains the same, the **Image** component will not recognize these modifications as a data change.
60
61### Image<sup>12+</sup>
62
63Image(src: PixelMap | ResourceStr | DrawableDescriptor | ImageContent)
64
65Obtains an image. The [ImageContent](#imagecontent12) type allows you to specify the image content.
66
67**Widget capability**: This API can be used in ArkTS widgets since API version 12.
68
69**Atomic service API**: This API can be used in atomic services since API version 12.
70
71**System capability**: SystemCapability.ArkUI.ArkUI.Full
72
73**Parameters**
74
75| Name | Type                                    | Mandatory  | Description                                    |
76| ---- | ---------------------------------------- | ---- | ---------------------------------------- |
77| src  | [PixelMap](../../apis-image-kit/arkts-apis-image-PixelMap.md) \| [ResourceStr](ts-types.md#resourcestr)\| [DrawableDescriptor](#drawabledescriptor10)\| [ImageContent](#imagecontent12) | 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>For details about how to use **PixelMap**, **ResourceStr**, and **DrawableDescriptor**, see the **scr** parameter description of [Image](#image-1).<br> [ImageContent](#imagecontent12): image content.<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.|
78
79### Image<sup>12+</sup>
80
81Image(src: PixelMap | ResourceStr | DrawableDescriptor, imageAIOptions: ImageAIOptions)
82
83Obtains an image. The [imageAIOptions](ts-image-common.md#imageaioptions) parameter allows you to set AI image analysis options.
84
85**Atomic service API**: This API can be used in atomic services since API version 12.
86
87**System capability**: SystemCapability.ArkUI.ArkUI.Full
88
89**Parameters**
90
91| Name | Type                                    | Mandatory  | Description                                    |
92| ---- | ---------------------------------------- | ---- | ---------------------------------------- |
93| src  | [PixelMap](../../apis-image-kit/arkts-apis-image-PixelMap.md) \| [ResourceStr](ts-types.md#resourcestr)\| [DrawableDescriptor](#drawabledescriptor10) | 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>For details about how to use **PixelMap**, **ResourceStr**, and **DrawableDescriptor**, see the **scr** parameter description of [Image](#image-1).<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.|
94| imageAIOptions  | [ImageAIOptions](ts-image-common.md#imageaioptions) | Yes  | AI image analysis options. You can configure the analysis type or bind an analyzer controller through this parameter.|
95
96## Attributes
97
98For details about how to use the attributes, see [Setting Attributes](../../../ui/arkts-graphics-display.md#setting-attributes). In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported.
99
100> **NOTE**
101>
102> The **Image** component does not support the universal attribute [foregroundColor](./ts-universal-attributes-foreground-color.md#foregroundcolor). Instead, you can set the fill color using the component's [fillColor](#fillcolor) attribute.
103
104### alt
105
106alt(value: string | Resource  | PixelMap)
107
108Sets the placeholder image displayed during loading.
109
110The placeholder image supports configuration of [objectFit](#objectfit) for setting the fill effect, which is consistent with the fill effect of the image.
111
112This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
113
114**Widget capability**: This API can be used in ArkTS widgets since API version 9.
115
116**Atomic service API**: This API can be used in atomic services since API version 11.
117
118**System capability**: SystemCapability.ArkUI.ArkUI.Full
119
120**Parameters**
121
122| Name| Type                                                    | Mandatory| Description                                                        |
123| ------ | -------------------------------------------------------- | ---- | ------------------------------------------------------------ |
124| value  | string \| [Resource](ts-types.md#resource) \| [PixelMap](../../apis-image-kit/arkts-apis-image-PixelMap.md)<sup>12+</sup> | Yes  | Placeholder image displayed during loading. Local images (in PNG, JPG, BMP, SVG, GIF, or HEIF format) and [PixelMap](../../apis-image-kit/arkts-apis-image-PixelMap.md) objects are supported, but online images are not.<br>Default value: **null**.<br>When the value is switched from a valid one (an image resource that can be parsed and loaded correctly) to an invalid one (an image path that cannot be parsed or loaded), the component retains the previously successfully loaded image content without clearing or resetting it.|
125
126### objectFit
127
128objectFit(value: ImageFit)
129
130Sets how the image is resized to fit its container.
131
132**Widget capability**: This API can be used in ArkTS widgets since API version 9.
133
134**Atomic service API**: This API can be used in atomic services since API version 11.
135
136**System capability**: SystemCapability.ArkUI.ArkUI.Full
137
138**Parameters**
139
140| Name| Type                                     | Mandatory| Description                                       |
141| ------ | ----------------------------------------- | ---- | ------------------------------------------- |
142| value  | [ImageFit](ts-appendix-enums.md#imagefit) | Yes  | How the image is resized to fit its container.<br>Default value: **ImageFit.Cover**|
143
144### imageMatrix<sup>15+</sup>
145
146imageMatrix(matrix: ImageMatrix)
147
148Sets the transformation matrix of the image. This API allows you to use the APIs provided by the [ImageMatrix](#imagematrix15) object, such as translate, rotate, and scale, to achieve the optimal display of grid thumbnails. This attribute is not applicable to SVG images.
149
150This attribute does not take effect when the **resizable** or **objectRepeat** attributes are set. This attribute only processes the image source and does not trigger any callback events of the **Image** component.
151
152This attribute is strongly related to the [objectFit](#objectfit) setting and only works when [objectFit](#objectfit) is set to **[ImageFit](ts-appendix-enums.md#imagefit).MATRIX**.
153
154**Atomic service API**: This API can be used in atomic services since API version 15.
155
156**System capability**: SystemCapability.ArkUI.ArkUI.Full
157
158**Parameters**
159
160| Name| Type                                                | Mandatory| Description          |
161| ------ | --------------------------------------------------- | ---- | -------------- |
162| matrix  | [ImageMatrix](#imagematrix15) | Yes  | Transformation matrix of the image.|
163
164### objectRepeat
165
166objectRepeat(value: ImageRepeat)
167
168Sets how the image is repeated. When set to repeat, the image is repeated from the center to edges, and the last image will be clipped if it does not fit in the component. This attribute is not applicable to SVG images.
169
170This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
171
172**Widget capability**: This API can be used in ArkTS widgets since API version 9.
173
174**Atomic service API**: This API can be used in atomic services since API version 11.
175
176**System capability**: SystemCapability.ArkUI.ArkUI.Full
177
178**Parameters**
179
180| Name| Type                                           | Mandatory| Description                                             |
181| ------ | ----------------------------------------------- | ---- | ------------------------------------------------- |
182| value  | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Yes  | How the image is repeated.<br>Default value: **ImageRepeat.NoRepeat**|
183
184### interpolation
185
186interpolation(value: ImageInterpolation)
187
188Sets the interpolation effect of the image, which can alleviate aliasing that occurs when the image is zoomed. This attribute is not applicable to SVG images.
189
190This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
191
192**Widget capability**: This API can be used in ArkTS widgets since API version 9.
193
194**Atomic service API**: This API can be used in atomic services since API version 11.
195
196**System capability**: SystemCapability.ArkUI.ArkUI.Full
197
198**Parameters**
199
200| Name| Type                                     | Mandatory| Description                                               |
201| ------ | ----------------------------------------- | ---- | --------------------------------------------------- |
202| value  | [ImageInterpolation](#imageinterpolation) | Yes  | Interpolation effect of the image.<br>Default value: **ImageInterpolation.Low**.<br>When set to **undefined**, the value is treated as **ImageInterpolation.None**.|
203
204### renderMode
205
206renderMode(value: ImageRenderMode)
207
208Sets the rendering mode of the image. This attribute is not applicable to SVG images.
209
210When [ColorFilter](#colorfilter9) is set, this attribute is not effective.
211
212This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
213
214**Widget capability**: This API can be used in ArkTS widgets since API version 9.
215
216**Atomic service API**: This API can be used in atomic services since API version 11.
217
218**System capability**: SystemCapability.ArkUI.ArkUI.Full
219
220**Parameters**
221
222| Name| Type                               | Mandatory| Description                                                        |
223| ------ | ----------------------------------- | ---- | ------------------------------------------------------------ |
224| value  | [ImageRenderMode](#imagerendermode) | Yes  | Rendering mode of the image, which can be **Original** or **Template** (monochrome).<br>Default value: **ImageRenderMode.Original**|
225
226### sourceSize
227
228sourceSize(value: ImageSourceSize)
229
230Sets the decoding size of the image. This attribute works only when the target size is smaller than the source size. This attribute is not applicable to SVG images or **PixelMap** objects.
231
232This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
233
234**Widget capability**: This API can be used in ArkTS widgets since API version 9.
235
236**Atomic service API**: This API can be used in atomic services since API version 11.
237
238**System capability**: SystemCapability.ArkUI.ArkUI.Full
239
240**Parameters**
241
242| Name| Type                                                   | Mandatory| Description                                                        |
243| ------ | ------------------------------------------------------- | ---- | ------------------------------------------------------------ |
244| value  | [ImageSourceSize](#imagesourcesize18) | Yes  | Decoding size of the image. This parameter 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.|
245
246### matchTextDirection
247
248matchTextDirection(value: boolean)
249
250Specifies whether the image follows the system language direction, displaying a mirrored effect in a right-to-left (RTL) language environments.
251
252This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
253
254**Widget capability**: This API can be used in ArkTS widgets since API version 9.
255
256**Atomic service API**: This API can be used in atomic services since API version 11.
257
258**System capability**: SystemCapability.ArkUI.ArkUI.Full
259
260**Parameters**
261
262| Name| Type   | Mandatory| Description                                        |
263| ------ | ------- | ---- | -------------------------------------------- |
264| value  | boolean | Yes  | Whether the image follows the system language direction, displaying a mirrored effect in a RTL language environments.<br>Default value: **false**.<br>The value **true** means that the image follows the system language direction, displaying a mirrored effect in a RTL language environments, and **false** means the opposite.|
265
266### fitOriginalSize
267
268fitOriginalSize(value: boolean)
269
270Specifies whether the image display size follows the size of the image source.
271
272This attribute does not take effect when:
273
274- The component has the **width** and **height** attributes set.
275- The parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
276
277**Widget capability**: This API can be used in ArkTS widgets since API version 9.
278
279**Atomic service API**: This API can be used in atomic services since API version 11.
280
281**System capability**: SystemCapability.ArkUI.ArkUI.Full
282
283**Parameters**
284
285| Name| Type   | Mandatory| Description                                            |
286| ------ | ------- | ---- | ------------------------------------------------ |
287| value  | boolean | Yes  | Whether the image display size follows the size of the image source.<br>Default value: **false**.<br>**NOTE**<br>**false** or not set: The image display size does not follow the size of the image source.<br>**true**: The image display size follows the size of the image source. |
288
289### fillColor
290
291fillColor(value: ResourceColor)
292
293Sets the fill color to be superimposed on the image. This attribute applies only to SVG images. Once set, the fill color will replace the fill colors of all drawable elements within the SVG image. To set the fill color for a PNG image, use [colorFilter](#colorfilter9).
294
295This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
296
297**Widget capability**: This API can be used in ArkTS widgets since API version 9.
298
299**Atomic service API**: This API can be used in atomic services since API version 11.
300
301**System capability**: SystemCapability.ArkUI.ArkUI.Full
302
303**Parameters**
304
305| Name| Type                                      | Mandatory| Description          |
306| ------ | ------------------------------------------ | ---- | -------------- |
307| value  | [ResourceColor](ts-types.md#resourcecolor) | Yes  | Fill color to be superimposed on the image.<br>**NOTE**<br> By default, no fill color is applied. If an invalid value is passed, the system uses the default theme color: black in light mode and white in dark mode.|
308
309### fillColor<sup>15+</sup>
310
311fillColor(color: ResourceColor|ColorContent)
312
313Sets the fill color to be superimposed on the image. This attribute applies only to SVG images. Once set, the fill color will replace the fill colors of all drawable elements within the SVG image. To set the fill color for a PNG image, use [colorFilter](#colorfilter9). To reset the fill color, pass a value of the [ColorContent](#colorcontent15) type.
314
315This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
316
317**Atomic service API**: This API can be used in atomic services since API version 15.
318
319**System capability**: SystemCapability.ArkUI.ArkUI.Full
320
321**Parameters**
322
323| Name| Type                                      | Mandatory| Description          |
324| ------ | ------------------------------------------ | ---- | -------------- |
325| color  | [ResourceColor](ts-types.md#resourcecolor)\|[ColorContent](#colorcontent15) | Yes  | Fill color to be superimposed on the image.<br>**NOTE**<br> By default, no fill color is applied. If an invalid value is passed, the system uses the default theme color: black in light mode and white in dark mode.|
326
327### fillColor<sup>20+</sup>
328
329fillColor(color: ResourceColor|ColorContent|ColorMetrics)
330
331Sets the fill color to be superimposed on the image. This attribute applies only to SVG images. Once set, the fill color will replace the fill colors of all drawable elements within the SVG image. To set the fill color for a PNG image, use [colorFilter](#colorfilter9). To reset the fill color, pass a value of the [ColorContent](#colorcontent15) type. You can set P3 color gamut values by passing in the [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) type, which can achieve richer color performance on devices that support high color gamut.
332
333This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
334
335**Atomic service API**: This API can be used in atomic services since API version 20.
336
337**System capability**: SystemCapability.ArkUI.ArkUI.Full
338
339**Parameters**
340
341| Name| Type                                      | Mandatory| Description          |
342| ------ | ------------------------------------------ | ---- | -------------- |
343| color  | [ResourceColor](ts-types.md#resourcecolor)\|[ColorContent](#colorcontent15)\|[ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes  | Fill color to be superimposed on the image.<br>**NOTE**<br> By default, no fill color is applied. If an invalid value is passed, the system uses the default theme color: black in light mode and white in dark mode.|
344
345### autoResize
346
347autoResize(value: boolean)
348
349Specifies whether to resize the image source based on the size of the display area during image decoding. 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**, but this may increase the memory usage.
350
351If the original image size does not match the display size, the image may be distorted or blurred. Recommended configuration for the optimal definition:
352
353When the image is scaled down: .autoResize(false) + .interpolation(.Medium)
354
355When the image is scaled up: .interpolation(.High)
356
357This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12) or the image format is SVG.
358
359**Widget capability**: This API can be used in ArkTS widgets since API version 9.
360
361**Atomic service API**: This API can be used in atomic services since API version 11.
362
363**System capability**: SystemCapability.ArkUI.ArkUI.Full
364
365**Parameters**
366
367| Name| Type   | Mandatory| Description                                                        |
368| ------ | ------- | ---- | ------------------------------------------------------------ |
369| value  | boolean | Yes  | 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: **false**.<br>**true**: Enable resizing.<br>**false**: Disable resizing.|
370
371### syncLoad<sup>8+</sup>
372
373syncLoad(value: boolean)
374
375Specifies whether to load the image synchronously. 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.
376
377This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
378
379If image flickering occurs during loading, set **syncLoad** to **true**. For details, see [Optimizing Concurrent Tasks](https://developer.huawei.com/consumer/en/doc/best-practices/bpta-click-to-click-response-optimization#section715115119192).
380
381**Widget capability**: This API can be used in ArkTS widgets since API version 9.
382
383**Atomic service API**: This API can be used in atomic services since API version 11.
384
385**System capability**: SystemCapability.ArkUI.ArkUI.Full
386
387**Parameters**
388
389| Name| Type   | Mandatory| Description                                                        |
390| ------ | ------- | ---- | ------------------------------------------------------------ |
391| value  | boolean | Yes  | 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>**true**: Load the image synchronously.<br>**false**.: Load the image asynchronously.|
392
393### copyOption<sup>9+</sup>
394
395copyOption(value: CopyOptions)
396
397Whether the image can be copied. 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. SVG images cannot be copied.
398
399This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
400
401**Widget capability**: This API can be used in ArkTS widgets since API version 9.
402
403**Atomic service API**: This API can be used in atomic services since API version 11.
404
405**System capability**: SystemCapability.ArkUI.ArkUI.Full
406
407**Parameters**
408
409| Name| Type                                            | Mandatory| Description                                         |
410| ------ | ------------------------------------------------ | ---- | --------------------------------------------- |
411| value  | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Yes  | Specifies whether the image can be copied.<br>Default value: **CopyOptions.None**|
412
413### colorFilter<sup>9+</sup>
414
415colorFilter(value: ColorFilter | DrawingColorFilter)
416
417Sets the color filter for the image.
418
419When this attribute is set, [renderMode](#rendermode) is not effective.
420
421**Widget capability**: This API can be used in ArkTS widgets since API version 9.
422
423**Atomic service API**: This API can be used in atomic services since API version 11.
424
425**System capability**: SystemCapability.ArkUI.ArkUI.Full
426
427**Parameters**
428
429| Name| Type                                   | Mandatory| Description                                                        |
430| ------ | --------------------------------------- | ---- | ------------------------------------------------------------ |
431| value  | [ColorFilter](ts-types.md#colorfilter9) \| [DrawingColorFilter](#drawingcolorfilter12) | Yes  | 1. Color filter of the image. The input parameter is a 4 x 5 RGBA transformation matrix.<br>The first row of the matrix represents vector values for R (red), the second row for G (green), the third row for B (blue), and the fourth row for A (alpha).<br>When the diagonal values of the matrix are 1 and all other values are 0, the original colors of the image are retained.<br> **Calculation rule:**<br>If the input filter matrix is as follows (value range: [0, 1]):<br>![image-matrix-1](figures/image_matrix_1.png) <br>And the pixel point is [R, G, B, A] with color values in the [0, 255] range,<br>then the color after filtering is [R', G', B', A'].<br>![image-matrix-2](figures/image_matrix_2.png)<br>2. The ColorFilter type of **@ohos.graphics.drawing** can be used as an input parameter since API version 12.<br>**NOTE**<br>This parameter is not available for SVG images in API version 11 and earlier versions.<br>The DrawingColorfilter type can be used in atomic services since API version 12. For SVG sources, the effect only applies when the **stroke** property is set (regardless of the value).|
432### draggable<sup>9+</sup>
433
434draggable(value: boolean)
435
436Specifies whether the image is draggable.
437
438**Atomic service API**: This API can be used in atomic services since API version 11.
439
440**System capability**: SystemCapability.ArkUI.ArkUI.Full
441
442**Parameters**
443
444| Name| Type   | Mandatory| Description                                                        |
445| ------ | ------- | ---- | ------------------------------------------------------------ |
446| value  | boolean | Yes  | Whether the image is draggable. The value **true** means that the image is draggable, in which case the bound long press gesture will not take effect.<br>Default value:<br>API version 9 and earlier: **false**<br> Since API version 10: **true**<br> To bind custom gestures to the component, set **draggable** to **false**. With the value **false**, drag-related events are not triggered.|
447
448### enableAnalyzer<sup>11+</sup>
449
450enableAnalyzer(enable: boolean)
451
452Sets whether to enable the AI image analyzer, which supports subject recognition, text recognition, and object lookup.<!--RP3--><!--RP3End-->
453
454This attribute cannot be used together with the [overlay](ts-universal-attributes-overlay.md) attribute. If they are set at the same time, the **CustomBuilder** attribute in **overlay** has no effect. This attribute depends on device capabilities.
455
456Images to be analyzed must be static, non-vector images. That is, SVG and GIF images cannot be analyzed. [Pixel maps](../../apis-image-kit/arkts-apis-image-PixelMap.md) in [RGBA_8888](../../apis-image-kit/arkts-apis-image-e.md#pixelmapformat7) format can be passed in for analysis. For details, see [Example 5: Enabling the AI Image Analyzer](#example-5-enabling-the-ai-image-analyzer).
457
458The placeholder images (specified by **alt**) cannot be analyzed. An image can be analyzed only when **objectRepeat** is set to **ImageRepeat.NoRepeat** and [obscured](ts-universal-attributes-obscured.md) is disabled.
459
460Analysis is performed based on the complete original image. If the **clip**, **margin**, **borderRadius**, **position**, or **objectFit** attribute is set, the image is not displayed completely. If **renderMode** is used to apply a mask, analysis is still performed based on the complete original image. The **copyOption** attribute does not affect the AI image analyzer functionality.
461
462This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
463
464> **NOTE**
465>
466> The ohos.permission.INTERNET permission must be declared.
467
468**Atomic service API**: This API can be used in atomic services since API version 12.
469
470**System capability**: SystemCapability.ArkUI.ArkUI.Full
471
472**Parameters**
473
474| Name| Type   | Mandatory| Description                                                        |
475| ------ | ------- | ---- | ------------------------------------------------------------ |
476| enable  | boolean | Yes  | Whether to enable the AI image analyzer.<br>Default value: **false**<br>**true**: Enable the AI image analyzer.<br>**false**: Disable the AI image analyzer.|
477
478### resizable<sup>11+</sup>
479
480resizable(value: ResizableOptions)
481
482Sets the resizable image options. Resizing is effective for drag previews and placeholder images.
483
484When [ResizableOptions](#resizableoptions11) is set to a valid value, neither **objectRepeat** nor **orientation** has effect.
485
486When the sum of the values of **top** and **bottom** is greater than the source image height, or the sum of the values of **left** and **right** is greater than the source image width, the [ResizableOptions](#resizableoptions11) attribute does not take effect.
487
488This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12) or the image format is SVG.
489
490**Atomic service API**: This API can be used in atomic services since API version 12.
491
492**System capability**: SystemCapability.ArkUI.ArkUI.Full
493
494**Parameters**
495
496| Name| Type                                   | Mandatory| Description                            |
497| ------ | --------------------------------------- | ---- | -------------------------------- |
498| value  | [ResizableOptions](#resizableoptions11) | Yes  | Resizable image options.|
499
500### privacySensitive<sup>12+</sup>
501
502privacySensitive(supported: boolean)
503
504Sets whether to secure sensitive information on widgets.
505
506**Widget capability**: This API can be used in ArkTS widgets since API version 12.
507
508**Atomic service API**: This API can be used in atomic services since API version 12.
509
510**System capability**: SystemCapability.ArkUI.ArkUI.Full
511
512**Parameters**
513
514| Name   | Type   | Mandatory| Description                    |
515| --------- | ------- | ---- | ------------------------ |
516| supported | boolean | Yes  | Whether to secure sensitive information on widgets.<br>**false** (default): Do not secure sensitive information on widgets.<br>**true**: Secure sensitive information on widgets, obscuring the image with a semi-transparent background style in privacy mode.<br>**NOTE**<br>If this parameter is set to **null**, the image is not obscured.<br>Obscuring requires [widget framework support](./ts-universal-attributes-obscured.md).|
517
518### dynamicRangeMode<sup>12+</sup>
519
520dynamicRangeMode(value: DynamicRangeMode)
521
522Sets the dynamic range of the image to be displayed. This attribute is not applicable to SVG images.
523
524<!--RP1--><!--RP1End-->
525
526**Atomic service API**: This API can be used in atomic services since API version 12.
527
528**System capability**: SystemCapability.ArkUI.ArkUI.Full
529
530**Parameters**
531
532| Name| Type                                   | Mandatory| Description                            |
533| ------ | --------------------------------------- | ---- | -------------------------------- |
534| value  | [DynamicRangeMode](#dynamicrangemode12) | Yes  | Dynamic range of the image.<br>Default value: **DynamicRangeMode.STANDARD**.|
535
536### orientation<sup>14+</sup>
537
538orientation(orientation: ImageRotateOrientation)
539
540Sets the display orientation of the image content.
541
542**Atomic service API**: This API can be used in atomic services since API version 14.
543
544**System capability**: SystemCapability.ArkUI.ArkUI.Full
545
546**Parameters**
547
548| Name| Type                                   | Mandatory| Description                            |
549| ------ | --------------------------------------- | ---- | -------------------------------- |
550| orientation  | [ImageRotateOrientation](#imagerotateorientation14) | Yes  | Display orientation of the image content.<br>GIF and SVG images are not supported.<br>For images containing rotation or flip information, use **ImageRotateOrientation.AUTO**.<br>Default value: **ImageRotateOrientation.UP**<br>When set to **undefined**, the value is treated as **ImageRotateOrientation.AUTO**.|
551
552### hdrBrightness<sup>19+</sup>
553
554hdrBrightness(brightness: number)
555
556Sets the brightness of HDR images displayed by the component.
557
558This attribute is not applicable to SVG images.
559
560If this attribute and the [dynamicRangeMode](#dynamicrangemode12) attribute are both set, [dynamicRangeMode](#dynamicrangemode12) does not take effect.
561
562**Atomic service API**: This API can be used in atomic services since API version 19.
563
564**System capability**: SystemCapability.ArkUI.ArkUI.Full
565
566**Parameters**
567
568| Name  | Type   | Mandatory| Description                  |
569| -------- | ------- | ---- | ---------------------- |
570| brightness | number | Yes  | Brightness of HDR images displayed by the component. This API only takes effect for HDR image sources.<br>Default value: **1.0**.<br>Value range: [0.0, 1.0]. Values less than 0 or greater than 1.0 are treated as **1.0**. **0**: The image is displayed at SDR brightness.<br>**1**: The image is displayed at the highest allowed HDR brightness. |
571
572## ImageContent<sup>12+</sup>
573
574Defines the image content.
575
576**Widget capability**: This API can be used in ArkTS widgets since API version 12.
577
578**Atomic service API**: This API can be used in atomic services since API version 12.
579
580**System capability**: SystemCapability.ArkUI.ArkUI.Full
581
582| Name    | Value   | Description                   |
583| ------ | ----- | -------------------------- |
584| EMPTY   | 0  | Empty image.                  |
585
586## ImageInterpolation
587
588Interpolation effect of the image.
589
590**Widget capability**: This API can be used in ArkTS widgets since API version 9.
591
592**Atomic service API**: This API can be used in atomic services since API version 11.
593
594**System capability**: SystemCapability.ArkUI.ArkUI.Full
595
596| Name    | Value| Description                      |
597| ------ | - | -------------------------- |
598| None   | 0 | Nearest neighbor interpolation.                  |
599| Low    | 1 | Bilinear interpolation.                    |
600| Medium | 2 | MipMap interpolation.                    |
601| High   | 3 | Cubic interpolation. This mode produces scaled images of the highest possible quality, but may require more image rendering time.|
602
603## ImageRenderMode
604
605Enumerates the rendering modes of images.
606
607**Widget capability**: This API can be used in ArkTS widgets since API version 9.
608
609**Atomic service API**: This API can be used in atomic services since API version 11.
610
611**System capability**: SystemCapability.ArkUI.ArkUI.Full
612
613| Name    | Value| Description          |
614| -------- | - | -------------- |
615| Original | 0 | Render image pixels as they are in the original source image.|
616| Template | 1 | Render image pixels to create a monochrome template image.|
617
618## ResizableOptions<sup>11+</sup>
619
620Defines the resizable image options.
621
622**Atomic service API**: This API can be used in atomic services since API version 12.
623
624**System capability**: SystemCapability.ArkUI.ArkUI.Full
625
626| Name| Type| Mandatory| Description|
627| --------- |-----------|-----------|-----------|
628| slice | [EdgeWidths](#edgewidths) |  No | Edge widths in different directions of a component.<br>**NOTE**<br>This parameter takes effect only when values of **bottom** and **right** are both greater than 0.<br> When a number is passed, the default unit is vp.|
629| lattice<sup>12+</sup> | [DrawingLattice](#drawinglattice12) |  No | Lattice object, which is used to divide the image by lattice.<br>**NOTE**<br> A lattice object can be created through the **createImageLattice** API of the **@ohos.graphics.drawing** module. The lattices on both even columns and even rows are fixed.<br>This parameter does not take effect for the [backgroundImageResizable](ts-universal-attributes-background.md#backgroundimageresizable12) API.<br> When a number is passed, the default unit is px.|
630
631## EdgeWidths
632
633Edge widths in different directions of a component.
634
635**Atomic service API**: This API can be used in atomic services since API version 11.
636
637**System capability**: SystemCapability.ArkUI.ArkUI.Full
638
639| Name| Type| Mandatory| Description|
640| --------- |-----------|-----------|-----------|
641|  top    |  [Length](ts-types.md#length)  |  No | Pixel value of the image that remains unchanged when the top side of the image is stretched.<br>Default value: **0**<br>Unit: vp|
642|  right  |  [Length](ts-types.md#length)  |  No | Pixel value of the image that remains unchanged when the right side of the image is stretched.<br>Default value: **0**<br>Unit: vp|
643|  bottom |  [Length](ts-types.md#length)  |  No | Pixel value of the image that remains unchanged when the bottom side of the image is stretched.<br>Default value: **0**<br>Unit: vp|
644|  left   |  [Length](ts-types.md#length)  |  No | Pixel value of the image that remains unchanged when the left side of the image is stretched.<br>Default value: **0**<br>Unit: vp|
645
646![edgewidths](figures/edgewidths.png)
647
648## DynamicRangeMode<sup>12+</sup>
649
650Describes the dynamic range of the image to be displayed.
651
652**Atomic service API**: This API can be used in atomic services since API version 12.
653
654**System capability**: SystemCapability.ArkUI.ArkUI.Full
655
656| Name    | Value   | Description                   |
657| ------ | -------------------------- | -------------------------- |
658| HIGH   | 0  | Unrestricted dynamic range, which allows for the maximum brightening of an image.             |
659| CONSTRAINT | 1 | Restricted dynamic range, which brightens an image within certain constraints.         |
660| STANDARD | 2 | Standard dynamic range, which does not brighten an image.        |
661
662## ImageRotateOrientation<sup>14+</sup>
663
664Describes the desired display orientation for image content.
665
666**System capability**: SystemCapability.ArkUI.ArkUI.Full
667
668| Name    | Value   | Description                   |
669| ------ | -------------------------- | -------------------------- |
670| AUTO | 0 | Use EXIF metadata for display orientation, with support for rotation and mirroring.<br>**Atomic service API**: This API can be used in atomic services since API version 14.<br>![imageRotateOrientation_0](figures/imageRotateOrientation_0.png) |
671| UP | 1 | Display original pixel data without transformation.<br>**Atomic service API**: This API can be used in atomic services since API version 14.|
672| RIGHT | 2 | Display the image after rotating it 90 degrees clockwise.<br>**Atomic service API**: This API can be used in atomic services since API version 14.<br>![imageRotateOrientation_2](figures/imageRotateOrientation_2.png) |
673| DOWN | 3 | Display the image after rotating it 180 degrees clockwise.<br>**Atomic service API**: This API can be used in atomic services since API version 14.<br>![imageRotateOrientation_3](figures/imageRotateOrientation_3.png) |
674| LEFT | 4 | Display the image after rotating it 270 degrees clockwise.<br>**Atomic service API**: This API can be used in atomic services since API version 14.<br>![imageRotateOrientation_4](figures/imageRotateOrientation_4.png) |
675| UP_MIRRORED<sup>20+</sup> | 5 | Display the image after flipping it horizontally.<br>**Atomic service API**: This API can be used in atomic services since API version 20.<br>![imageRotateOrientation_5](figures/imageRotateOrientation_5.png) |
676| RIGHT_MIRRORED<sup>20+</sup> | 6 | Display the image after flipping it horizontally and then rotating it 90 degrees clockwise.<br>**Atomic service API**: This API can be used in atomic services since API version 20.<br>![imageRotateOrientation_6](figures/imageRotateOrientation_6.png) |
677| DOWN_MIRRORED<sup>20+</sup> | 7 | Display the image after flipping it vertically.<br>**Atomic service API**: This API can be used in atomic services since API version 20.<br>![imageRotateOrientation_7](figures/imageRotateOrientation_7.png) |
678| LEFT_MIRRORED<sup>20+</sup> | 8 | Display the image after flipping it horizontally and then rotating it 270 degrees clockwise.<br>**Atomic service API**: This API can be used in atomic services since API version 20.<br>![imageRotateOrientation_8](figures/imageRotateOrientation_8.png) |
679
680## ImageSourceSize<sup>18+</sup>
681
682Provides the image decoding size.
683
684**Widget capability**: This API can be used in ArkTS widgets since API version 18.
685
686**Atomic service API**: This API can be used in atomic services since API version 18.
687
688**System capability**: SystemCapability.ArkUI.ArkUI.Full
689
690| Name| Type      | Mandatory| Description          |
691| ------ | --------- | ---- | ------------- |
692| width<sup>7+</sup>  | number | Yes  | Width of the decoded image.<br>Unit: vp.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 9.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
693| height<sup>7+</sup>  | number | Yes  | Height of the decoded image.<br>Unit: vp.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 9.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
694
695## DrawableDescriptor<sup>10+</sup>
696
697type DrawableDescriptor = DrawableDescriptor
698
699Represents a parameter object for the **Image** component.
700
701**Atomic service API**: This API can be used in atomic services since API version 11.
702
703**System capability**: SystemCapability.ArkUI.ArkUI.Full
704
705| Type    | Description      |
706| ------ | ---------- |
707| [DrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#drawabledescriptor)  | **DrawableDescriptor** object.|
708
709## DrawingColorFilter<sup>12+</sup>
710
711type DrawingColorFilter = ColorFilter
712
713Represents a color filter object.
714
715**Atomic service API**: This API can be used in atomic services since API version 12.
716
717**System capability**: SystemCapability.ArkUI.ArkUI.Full
718
719| Type    | Description      |
720| ------ | ---------- |
721| [ColorFilter](../../apis-arkgraphics2d/arkts-apis-graphics-drawing-ColorFilter.md)  | Color filter created.|
722
723## DrawingLattice<sup>12+<sup>
724
725type DrawingLattice = Lattice
726
727Represents a matrix grid object that divides an image into a rectangular grid.
728
729**Atomic service API**: This API can be used in atomic services since API version 12.
730
731**System capability**: SystemCapability.ArkUI.ArkUI.Full
732
733| Type    | Description      |
734| ------ | ---------- |
735| [Lattice](../../apis-arkgraphics2d/arkts-apis-graphics-drawing-Lattice.md) | Matrix grid object used to divide the image into a rectangular grid.|
736
737## ImageMatrix<sup>15+</sup>
738
739type ImageMatrix = Matrix4Transit
740
741Represents the current matrix object.
742
743**Atomic service API**: This API can be used in atomic services since API version 15.
744
745**System capability**: SystemCapability.ArkUI.ArkUI.Full
746
747| Type    | Description      |
748| ------ | ---------- |
749| [Matrix4Transit](../js-apis-matrix4.md#matrix4transit) | Current matrix object.|
750
751## ColorContent<sup>15+</sup>
752
753Defines the content for color filling.
754
755**Atomic service API**: This API can be used in atomic services since API version 15.
756
757**System capability**: SystemCapability.ArkUI.ArkUI.Full
758
759| Name| Type      | Read-Only| Optional| Description          |
760| ------ | --------- | --- | --- | ------------- |
761| ORIGIN  | ColorContent | Yes| No| Resets the [fillColor](#fillcolor) API, effectively the same as not setting [fillColor](#fillcolor).|
762
763## Events
764
765In addition to the [universal events](ts-component-general-events.md), the following events are supported.
766
767### onComplete
768
769onComplete(callback: (event?: { width: number, height: number, componentWidth: number, componentHeight: number, loadingStatus: number,contentWidth: number, contentHeight: number, contentOffsetX: number, contentOffsetY: number }) =&gt; void)
770
771Triggered when an image is successfully loaded or decoded. The size of the loaded image is returned.
772
773This event is not triggered if the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
774
775**Widget capability**: This API can be used in ArkTS widgets since API version 9.
776
777**Atomic service API**: This API can be used in atomic services since API version 11.
778
779**System capability**: SystemCapability.ArkUI.ArkUI.Full
780
781**Parameters**
782
783| Name                      | Type  | Mandatory| Description                                                        |
784| ---------------------------- | ------ | ---- | ------------------------------------------------------------ |
785| width                        | number | Yes  | Width of the image.<br>Unit: pixel                                   |
786| height                       | number | Yes  | Height of the image.<br>Unit: pixel                                   |
787| componentWidth               | number | Yes  | Width of the component.<br>Unit: pixel                                   |
788| componentHeight              | number | Yes  | Height of the component.<br>Unit: pixel                                   |
789| loadingStatus                | number | Yes  | 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.|
790| contentWidth<sup>10+</sup>   | number | Yes  | 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**.|
791| contentHeight<sup>10+</sup>  | number | Yes  | 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**.|
792| contentOffsetX<sup>10+</sup> | number | Yes  | 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**.|
793| contentOffsetY<sup>10+</sup> | number | Yes  | 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**.|
794
795### onError<sup>9+</sup>
796
797onError(callback: ImageErrorCallback)
798
799Triggered when an error occurs during image loading.
800
801This event is not triggered if the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
802
803**Widget capability**: This API can be used in ArkTS widgets since API version 9.
804
805**Atomic service API**: This API can be used in atomic services since API version 11.
806
807**System capability**: SystemCapability.ArkUI.ArkUI.Full
808
809**Parameters**
810
811| Name  | Type                                      | Mandatory| Description                      |
812| -------- | ------------------------------------------ | ---- | -------------------------- |
813| callback | [ImageErrorCallback](#imageerrorcallback9) | Yes  | Callback triggered when an error occurs during image loading.<br>**NOTE**<br>Whenever possible, implement this callback to quickly identify failure reasons. For details, see the [ImageError error code reference](#imageerror9).|
814
815### onFinish
816
817onFinish(event: () =&gt; void)
818
819Triggered when the animation playback in the loaded SVG image is complete. If the animation is an infinite loop, this callback is not triggered.
820
821Only SVG images are supported. This event is not triggered if the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
822
823**Widget capability**: This API can be used in ArkTS widgets since API version 9.
824
825**Atomic service API**: This API can be used in atomic services since API version 11.
826
827**System capability**: SystemCapability.ArkUI.ArkUI.Full
828
829## ImageErrorCallback<sup>9+</sup>
830
831type ImageErrorCallback = (error: ImageError) => void
832
833Represents the callback triggered when an error occurs during image loading.
834
835The callback is not triggered if the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
836
837**Widget capability**: This API can be used in ArkTS widgets since API version 9.
838
839**Atomic service API**: This API can be used in atomic services since API version 11.
840
841**System capability**: SystemCapability.ArkUI.ArkUI.Full
842
843| Name| Type                      | Mandatory| Description                              |
844| ------ | -------------------------- | ---- | ---------------------------------- |
845| error  | [ImageError](#imageerror9) | Yes  | Return object that triggers the callback for when an error occurs during image loading.|
846
847## ImageError<sup>9+</sup>
848
849Describes the return object that triggers the callback for when an error occurs during image loading.
850
851This event is not triggered if the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
852
853**Widget capability**: This API can be used in ArkTS widgets since API version 9.
854
855**System capability**: SystemCapability.ArkUI.ArkUI.Full
856
857| Name         | Type  | Mandatory| Description                     |
858| --------------- | ------ | ---- | ------------------------- |
859| componentWidth  | number | Yes  | Width of the component.<br>Unit: pixel<br>**Widget capability**: This API can be used in ArkTS widgets since API version 9.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
860| componentHeight | number | Yes  | Height of the component.<br>Unit: pixel<br>**Widget capability**: This API can be used in ArkTS widgets since API version 9.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
861| message<sup>10+</sup>         | string | Yes  | Error information.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 10.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
862| error<sup>20+</sup>         | [BusinessError\<void>](#businesserror20) | No  | Error information returned when an error occurs during image loading, where **code** represents the error code and **message** indicates the error message. For details, see the **ImageError** error code reference below.<br>Default value: **{ code : -1, message : "" }**.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 20.<br>**Atomic service API**: This API can be used in atomic services since API version 20.|
863
864## BusinessError<sup>20+</sup>
865
866type BusinessError\<T> = BusinessError\<T>
867
868Represents the error information returned when an error occurs during image loading.
869
870**Widget capability**: This API can be used in ArkTS widgets since API version 20.
871
872**Atomic service API**: This API can be used in atomic services since API version 20.
873
874**System capability**: SystemCapability.ArkUI.ArkUI.Full
875
876| Type | Description  |
877| ---- | ------ |
878| [BusinessError\<T>](../../apis-basic-services-kit/js-apis-base.md#businesserror) | Error information returned when an error occurs during image loading.|
879
880The table below describes the **ImageError** error codes. The **error** property of **ImageError** contains error details with **code** and **message** fields, representing the error code and error message, respectively.
881
882| ID | Error Message                      | Stage of Occurrence| Image Type|
883| --------  | ----------------------------   | --------- | ------- |
884| 101000    | unknown source type.           | Data loading| Unknown|
885| 102010    | sync http task of uri cancelled. | Data loading| Network file|
886| 102011    | sync http task of uri failed.  | Data loading| Network file|
887| 102012    | async http task of uri cancelled. | Data loading| Network file|
888| 102013    | async http task of uri failed. | Data loading| Network file|
889| 102030    | wrong code format.             | Data loading| Base64 string file|
890| 102031    | decode base64 image failed.    | Data loading| Base64 string file|
891| 102050    | path is too long.              | Data loading| Base64 string file|
892| 102051    | read data failed.              | Data loading| Sandbox file|
893| 102070    | get image data by name failed. | Data loading| Sandbox file|
894| 102071    | get image data by id failed.   | Data loading| Resource file|
895| 102072    | uri is invalid.                | Data loading| Resource file|
896| 102090    | uri is invalid.                | Data loading| In-package file|
897| 102091    | get asset failed.              | Data loading| In-package file|
898| 102110    | open file failed.              | Data loading| Media library file|
899| 102111    | get file stat failed.          | Data loading| Media library file|
900| 102112    | read file failed.              | Data loading| Media library file|
901| 102130    | decoded data is empty.         | Data loading| Media library thumbnail|
902| 102131    | load shared memory image data timeout. | Data loading| Shared memory file|
903| 103100    | make svg dom failed.           | Data loading| Vector graphics file|
904| 103200    | image data size is invalid.    | Data loading| Bitmap file|
905| 111000    | image source create failed.    | Data decoding| Bitmap file|
906| 111001    | pixelmap create failed.        | Data decoding| Bitmap file|
907
908## Example
909
910### Example 1: Loading Images of Basic Types
911
912This example demonstrates how to load images of basic types, such as PNG, GIF, SVG, and JPG, by passing in [Resource](ts-types.md#resource) resources.
913
914```ts
915@Entry
916@Component
917struct ImageExample1 {
918  build() {
919    Column() {
920      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
921        Row() {
922          // Load a PNG image.
923          Image($r('app.media.ic_camera_master_ai_leaf'))
924            .width(110).height(110).margin(15)
925            .overlay('png', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
926          // Load a GIF image.
927          Image($r('app.media.loading'))
928            .width(110).height(110).margin(15)
929            .overlay('gif', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
930        }
931        Row() {
932          // Load an SVG image.
933          Image($r('app.media.ic_camera_master_ai_clouded'))
934            .width(110).height(110).margin(15)
935            .overlay('svg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
936          // Load a JPG image.
937          Image($r('app.media.ic_public_favor_filled'))
938            .width(110).height(110).margin(15)
939            .overlay('jpg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
940        }
941      }
942    }.height(320).width(360).padding({ right: 10, top: 10 })
943  }
944}
945```
946
947![en-us_image_0000001592882500](figures/en-us_image_0000001592882500.gif)
948
949### Example 2: Downloading and Displaying Static Online Images
950
951The default timeout is 5 minutes for loading online images. When using an online image, you are advised to use **alt** to configure a placeholder image displayed during loading. You can use [HTTP](../../../network/http-request.md) to send a network request, and then decode the returned data into a **PixelMap** object for the **Image** component. Note that a GIF image loaded into a **PixelMap** object will be displayed as a static image. For details about image development, see [Introduction to Image Kit](../../../media/image/image-overview.md).
952
953The **ohos.permission.INTERNET** permission is required for using online images. For details about how to apply for a permission, see [Declaring Permissions](../../../security/AccessToken/declare-permissions.md).
954
955```ts
956import { http } from '@kit.NetworkKit';
957import { BusinessError } from '@kit.BasicServicesKit';
958import { image } from '@kit.ImageKit';
959
960@Entry
961@Component
962struct ImageExample2 {
963  @State pixelMapImg: PixelMap | undefined = undefined;
964
965  aboutToAppear() {
966    this.requestImageUrl('https://www.example.com/xxx.png'); // Enter a specific online image URL.
967  }
968
969  requestImageUrl(url: string) {
970    http.createHttp().request(url, (error: BusinessError, data: http.HttpResponse)=> {
971      if (error) {
972        console.error(`request image failed: url: ${url}, code: ${error.code}, message: ${error.message}`);
973      } else {
974        let imgData: ArrayBuffer = data.result as ArrayBuffer;
975        console.info(`request image success, size: ${imgData.byteLength}`);
976        let imgSource: image.ImageSource = image.createImageSource(imgData);
977        class sizeTmp {
978          height: number = 100;
979          width: number = 100;
980        }
981        let options: Record<string, number | boolean | sizeTmp> = {
982          'alphaType': 0,
983          'editable': false,
984          'pixelFormat': 3,
985          'scaleMode': 1,
986          'size': { height: 100, width: 100 }
987        }
988        imgSource.createPixelMap(options).then((pixelMap: PixelMap) => {
989          console.error('image createPixelMap success');
990          this.pixelMapImg = pixelMap;
991        })
992        imgSource.release()
993      }
994    })
995  }
996
997  build() {
998    Column() {
999      Image(this.pixelMapImg)
1000        .alt($r('app.media.img'))
1001        .objectFit(ImageFit.None)
1002        .width('100%')
1003        .height('100%')
1004    }
1005  }
1006}
1007```
1008
1009![en-us_image_0000001607845173](figures/en-us_image_view2.png)
1010
1011### Example 3: Downloading and Displaying Online GIF Images
1012
1013This example shows how to use the [cacheDownload.download](../../apis-basic-services-kit/js-apis-request-cacheDownload.md#cachedownloaddownload) API to download online GIF images.
1014
1015The **ohos.permission.INTERNET** permission is required for using online images. For details about how to apply for a permission, see [Declaring Permissions](../../../security/AccessToken/declare-permissions.md).
1016
1017```ts
1018import { cacheDownload } from '@kit.BasicServicesKit';
1019
1020@Entry
1021@Component
1022struct Index {
1023  @State src: string = 'https://www.example.com/xxx.gif'; // Enter a specific online image URL.
1024
1025  async aboutToAppear(): Promise<void> {
1026    // Provide configuration options for the download-and-cache task.
1027    let options: cacheDownload.CacheDownloadOptions = {};
1028    try {
1029      // Download the resource. If the download is successful, the resource will be cached to the specified file in the application memory or sandbox directory.
1030      cacheDownload.download(this.src, options);
1031      console.error(`Resource downloaded successfully. `);
1032    } catch (err) {
1033      console.error(`Failed to download the resource. err: ${JSON.stringify(err)}`);
1034    }
1035  }
1036
1037  build() {
1038    Column() {
1039      // If src specifies an online image that has been successfully downloaded and cached, the image will be displayed without requiring re-downloading.
1040      Image(this.src)
1041        .width(100)
1042        .height(100)
1043        .objectFit(ImageFit.Cover)
1044        .borderWidth(1)
1045    }
1046    .height('100%')
1047    .width('100%')
1048  }
1049}
1050```
1051
1052### Example 4: Adding Events to an Image
1053
1054This example demonstrates how to add the [onClick](ts-universal-events-click.md#onclick) and [onFinish](#onfinish) events to an image.
1055
1056```ts
1057@Entry
1058@Component
1059struct ImageExample3 {
1060  private imageOne: Resource = $r('app.media.earth');
1061  private imageTwo: Resource = $r('app.media.star');
1062  private imageThree: Resource = $r('app.media.moveStar');
1063  @State src: Resource = this.imageOne;
1064  @State src2: Resource = this.imageThree;
1065  build(){
1066    Column(){
1067      // Add a click event so that a specific image is loaded upon clicking.
1068      Image(this.src)
1069        .width(100)
1070        .height(100)
1071        .onClick(() => {
1072          this.src = this.imageTwo;
1073        })
1074
1075      // When the image to be loaded is in SVG format:
1076      Image(this.src2)
1077        .width(100)
1078        .height(100)
1079        .onFinish(() => {
1080          // Load another image when the SVG image has finished its animation.
1081          this.src2 = this.imageOne;
1082        })
1083    }.width('100%').height('100%')
1084  }
1085}
1086```
1087
1088![en-us_image_0000001607845173](figures/en-us_image_0000001607845173.gif)
1089
1090### Example 5: Enabling the AI Image Analyzer
1091<!--RP2-->
1092This example shows how to enable the AI image analyzer using the [enableAnalyzer](#enableanalyzer11) API.
1093
1094```ts
1095import { image } from '@kit.ImageKit';
1096
1097@Entry
1098@Component
1099struct ImageExample4 {
1100  @State imagePixelMap: image.PixelMap | undefined = undefined;
1101  private aiController: ImageAnalyzerController = new ImageAnalyzerController();
1102  private options: ImageAIOptions = {
1103    types: [ImageAnalyzerType.SUBJECT, ImageAnalyzerType.TEXT],
1104    aiController: this.aiController
1105  };
1106
1107  async aboutToAppear() {
1108    this.imagePixelMap = await this.getPixmapFromMedia($r('app.media.app_icon'));
1109  }
1110
1111  build() {
1112    Column() {
1113      Image(this.imagePixelMap, this.options)
1114        .enableAnalyzer(true)
1115        .width(200)
1116        .height(200)
1117        .margin({bottom:10})
1118      Button('getTypes')
1119        .width(80)
1120        .height(80)
1121        .onClick(() => {
1122          this.aiController.getImageAnalyzerSupportTypes();
1123        })
1124    }
1125  }
1126  private async getPixmapFromMedia(resource: Resource) {
1127    let unit8Array = await this.getUIContext().getHostContext()?.resourceManager?.getMediaContent({
1128      bundleName: resource.bundleName,
1129      moduleName: resource.moduleName,
1130      id: resource.id
1131    });
1132    let imageSource = image.createImageSource(unit8Array?.buffer.slice(0, unit8Array.buffer.byteLength));
1133    let createPixelMap: image.PixelMap = await imageSource.createPixelMap({
1134      desiredPixelFormat: image.PixelMapFormat.RGBA_8888
1135    });
1136    await imageSource.release();
1137    return createPixelMap;
1138  }
1139}
1140```
1141
1142![en-us_image_0000001607845173](figures/en-us_image_view4.gif)
1143<!--RP2End-->
1144### Example 6: Stretching an Image Using slice
1145
1146This example demonstrates how to stretch an image in different directions using the **slice** option of the [resizable](#resizable11) attribute.
1147
1148```ts
1149@Entry
1150@Component
1151struct Index {
1152  @State top: number = 10;
1153  @State bottom: number = 10;
1154  @State left: number = 10;
1155  @State right: number = 10;
1156
1157  build() {
1158    Column({ space: 5 }) {
1159      // Original image effect
1160      Image($r("app.media.landscape"))
1161        .width(200).height(200)
1162        .border({ width: 2, color: Color.Pink })
1163        .objectFit(ImageFit.Contain)
1164
1165      // Set the resizable attribute to stretch the image in different directions.
1166      Image($r("app.media.landscape"))
1167        .resizable({
1168          slice: {
1169            // When a number is passed in, it uses the default vp unit, which is parsed into different px sizes on different devices. Choose the unit based on your needs.
1170            left: `${this.left}px`,
1171            right: `${this.right}px`,
1172            top: `${this.top}px`,
1173            bottom: `${this.bottom}px`
1174          }
1175        })
1176        .width(200)
1177        .height(200)
1178        .border({ width: 2, color: Color.Pink })
1179        .objectFit(ImageFit.Contain)
1180
1181      Row() {
1182        Button("add top to " + this.top).fontSize(10)
1183          .onClick(() => {
1184            this.top += 10;
1185          })
1186        Button("add bottom to " + this.bottom).fontSize(10)
1187          .onClick(() => {
1188            this.bottom += 10;
1189          })
1190      }
1191
1192      Row() {
1193        Button("add left to " + this.left).fontSize(10)
1194          .onClick(() => {
1195            this.left += 10;
1196          })
1197        Button("add right to " + this.right).fontSize(10)
1198          .onClick(() => {
1199            this.right += 10;
1200          })
1201      }
1202
1203    }
1204    .justifyContent(FlexAlign.Start).width('100%').height('100%')
1205  }
1206}
1207```
1208
1209![imageResizable](figures/imageResizable.gif)
1210
1211### Example 7: Stretching an Image Using lattice
1212
1213This example demonstrates how to stretch an image using the **lattice** option of the [resizable](#resizable11) attribute with a rectangular grid object.
1214
1215```ts
1216import { drawing } from '@kit.ArkGraphics2D';
1217
1218@Entry
1219@Component
1220struct drawingLatticeTest {
1221  private xDivs: Array<number> = [1, 2, 200];
1222  private yDivs: Array<number> = [1, 2, 200];
1223  private fXCount: number = 3;
1224  private fYCount: number = 3;
1225  private drawingLatticeFirst: DrawingLattice =
1226    drawing.Lattice.createImageLattice(this.xDivs, this.yDivs, this.fXCount, this.fYCount);
1227
1228  build() {
1229    Scroll() {
1230      Column({ space: 10 }) {
1231        Text('Original Image').fontSize(20).fontWeight(700)
1232        Column({ space: 10 }) {
1233          Image($r('app.media.mountain'))
1234            .width(260).height(260)
1235        }.width('100%')
1236
1237        Text('Resize by lattice').fontSize(20).fontWeight(700)
1238        Column({ space: 10 }) {
1239          Image($r('app.media.mountain'))
1240            .objectRepeat(ImageRepeat.X)
1241            .width(260)
1242            .height(260)
1243            .resizable({
1244              lattice: this.drawingLatticeFirst
1245            })
1246        }.width('100%')
1247      }.width('100%')
1248    }
1249  }
1250}
1251```
1252
1253![imageResizableLattice](figures/imageResizableLattice.png)
1254
1255### Example 8: Playing a PixelMap Array Animation
1256
1257This example demonstrates how to play an animation using a **PixelMap** array through an [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12) object.
1258
1259```ts
1260import {AnimationOptions, AnimatedDrawableDescriptor} from '@kit.ArkUI';
1261import { image } from '@kit.ImageKit';
1262
1263@Entry
1264@Component
1265struct ImageExample {
1266  pixelMaps: PixelMap[] = [];
1267  options: AnimationOptions = { iterations: 1 };
1268  @State animated: AnimatedDrawableDescriptor | undefined = undefined;
1269
1270  async aboutToAppear() {
1271    this.pixelMaps = await this.getPixelMaps();
1272    this.animated = new AnimatedDrawableDescriptor(this.pixelMaps, this.options);
1273  }
1274
1275  build() {
1276    Column() {
1277      Row() {
1278        Image(this.animated)
1279          .width('500px').height('500px')
1280          .onFinish(() => {
1281            console.info('finish');
1282          })
1283      }.height('50%')
1284      Row() {
1285        Button('once').width(100).padding(5).onClick(() => {
1286          this.options = { iterations: 1 };
1287          this.animated = new AnimatedDrawableDescriptor(this.pixelMaps, this.options);
1288        }).margin(5)
1289        Button('infinite').width(100).padding(5).onClick(() => {
1290          this.options = { iterations: -1 };
1291          this.animated = new AnimatedDrawableDescriptor(this.pixelMaps, this.options);
1292        }).margin(5)
1293      }
1294    }.width('50%')
1295  }
1296
1297  private async getPixmapListFromMedia(resource: Resource) {
1298    let unit8Array = await this.getUIContext().getHostContext()?.resourceManager?.getMediaContent({
1299      bundleName: resource.bundleName,
1300      moduleName: resource.moduleName,
1301      id: resource.id
1302    });
1303    let imageSource = image.createImageSource(unit8Array?.buffer.slice(0, unit8Array.buffer.byteLength));
1304    let createPixelMap: image.PixelMap[] = await imageSource.createPixelMapList({
1305      desiredPixelFormat: image.PixelMapFormat.RGBA_8888
1306    });
1307    await imageSource.release();
1308    return createPixelMap;
1309  }
1310
1311  private async getPixmapFromMedia(resource: Resource) {
1312    let unit8Array = await this.getUIContext().getHostContext()?.resourceManager?.getMediaContent({
1313      bundleName: resource.bundleName,
1314      moduleName: resource.moduleName,
1315      id: resource.id
1316    });
1317    let imageSource = image.createImageSource(unit8Array?.buffer.slice(0, unit8Array.buffer.byteLength));
1318    let createPixelMap: image.PixelMap = await imageSource.createPixelMap({
1319      desiredPixelFormat: image.PixelMapFormat.RGBA_8888
1320    });
1321    await imageSource.release();
1322    return createPixelMap;
1323  }
1324
1325  private async getPixelMaps() {
1326    let myPixelMaps:PixelMap[] = await this.getPixmapListFromMedia($r('app.media.mountain')); // Add images.
1327    myPixelMaps.push(await this.getPixmapFromMedia($r('app.media.sky')));
1328    myPixelMaps.push(await this.getPixmapFromMedia($r('app.media.clouds')));
1329    myPixelMaps.push(await this.getPixmapFromMedia($r('app.media.landscape')));
1330    return myPixelMaps;
1331  }
1332}
1333```
1334
1335![en-us_image_0000001607845173](figures/en-us_image_view6.gif)
1336
1337### Example 9: Setting a Color Filter for an Image
1338
1339This example shows how to set a color filter for an image using the [colorFilter](#colorfilter9) attribute.
1340
1341```ts
1342import { drawing, common2D } from '@kit.ArkGraphics2D';
1343
1344@Entry
1345@Component
1346struct ImageExample3 {
1347  private imageOne: Resource = $r('app.media.1');
1348  private imageTwo: Resource = $r('app.media.2');
1349  @State src: Resource = this.imageOne;
1350  @State src2: Resource = this.imageTwo;
1351  private colorFilterMatrix: number[] = [1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0];
1352  private color: common2D.Color = {
1353    alpha: 255,
1354    red: 255,
1355    green: 0,
1356    blue: 0
1357  };
1358  @State drawingColorFilterFirst: ColorFilter | undefined = undefined;
1359  @State drawingColorFilterSecond: ColorFilter | undefined = undefined;
1360  @State drawingColorFilterThird: ColorFilter | undefined = undefined;
1361
1362  build() {
1363    Column() {
1364      Image(this.src)
1365        .width(100)
1366        .height(100)
1367        .colorFilter(this.drawingColorFilterFirst)
1368        .onClick(()=>{
1369          this.drawingColorFilterFirst =
1370            drawing.ColorFilter.createBlendModeColorFilter(this.color, drawing.BlendMode.SRC_IN);
1371        })
1372
1373      Image(this.src2)
1374        .width(100)
1375        .height(100)
1376        .colorFilter(this.drawingColorFilterSecond)
1377        .onClick(()=>{
1378          this.drawingColorFilterSecond = new ColorFilter(this.colorFilterMatrix);
1379        })
1380
1381      // When the image to be loaded is in SVG format:
1382      Image($r('app.media.test_self'))
1383        .width(110)
1384        .height(110)
1385        .margin(15)
1386        .colorFilter(this.drawingColorFilterThird)
1387        .onClick(()=>{
1388          this.drawingColorFilterThird =
1389            drawing.ColorFilter.createBlendModeColorFilter(this.color, drawing.BlendMode.SRC_IN);
1390        })
1391    }
1392  }
1393}
1394```
1395![imageSetColorFilter](figures/imageSetColorFilter.gif)
1396
1397### Example 10: Setting the Fill Effect for an Image
1398
1399This example shows how to use the [objectFit](#objectfit) attribute to specify how an image is resized to fit its container.
1400
1401```ts
1402@Entry
1403@Component
1404struct ImageExample{
1405  build() {
1406    Column() {
1407      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
1408        Row() {
1409          // Load a PNG image.
1410          Image($r('app.media.sky'))
1411            .width(110).height(110).margin(15)
1412            .overlay('png', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
1413            .border({ width: 2, color: Color.Pink })
1414            .objectFit(ImageFit.TOP_START)
1415          // Load a GIF image.
1416          Image($r('app.media.loading'))
1417            .width(110).height(110).margin(15)
1418            .overlay('gif', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
1419            .border({ width: 2, color: Color.Pink })
1420            .objectFit(ImageFit.BOTTOM_START)
1421        }
1422        Row() {
1423          // Load an SVG image.
1424          Image($r('app.media.svg'))
1425            .width(110).height(110).margin(15)
1426            .overlay('svg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
1427            .border({ width: 2, color: Color.Pink })
1428            .objectFit(ImageFit.TOP_END)
1429          // Load a JPG image.
1430          Image($r('app.media.jpg'))
1431            .width(110).height(110).margin(15)
1432            .overlay('jpg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
1433            .border({ width: 2, color: Color.Pink })
1434            .objectFit(ImageFit.CENTER)
1435        }
1436      }
1437    }.height(320).width(360).padding({ right: 10, top: 10 })
1438  }
1439}
1440```
1441
1442![imageResizable](figures/imageSetFit.gif)
1443
1444### Example 11: Switching Between Different Types of Images
1445
1446This example demonstrates the effect of displaying images with [ResourceStr](ts-types.md#resourcestr) and [ImageContent](#imagecontent12) as types of data sources.
1447
1448```ts
1449@Entry
1450@Component
1451struct ImageContentExample {
1452  @State imageSrcIndex: number = 0;
1453  @State imageSrcList: (ResourceStr | ImageContent)[] = [$r('app.media.app_icon'), ImageContent.EMPTY];
1454
1455  build() {
1456    Column({ space: 10 }) {
1457      Image(this.imageSrcList[this.imageSrcIndex])
1458        .width(100)
1459        .height(100)
1460      Button('Change Image src')
1461        .padding(20)
1462        .onClick(() => {
1463          this.imageSrcIndex = (this.imageSrcIndex + 1) % this.imageSrcList.length;
1464        })
1465    }.width('100%')
1466    .padding(20)
1467  }
1468}
1469```
1470
1471![imageContent](figures/en-us_image_view9.gif)
1472
1473### Example 12: Securing Sensitive Information
1474
1475This example shows how to secure sensitive information on widgets using the [privacySensitive](#privacysensitive12) attribute. The display requires widget framework support.
1476
1477```ts
1478@Entry
1479@Component
1480struct ImageExample {
1481  build() {
1482    Column({ space: 10 }) {
1483      Image($r('app.media.startIcon'))
1484        .width(50)
1485        .height(50)
1486        .margin({top :30})
1487        .privacySensitive(true)
1488    }
1489    .alignItems(HorizontalAlign.Center)
1490    .width('100%')
1491  }
1492}
1493```
1494
1495![imageContent](figures/en-us_image_view10.gif)
1496
1497### Example 13: Setting the Scan Effect for an Image
1498
1499This example shows how to enable the scan effect for an image using [linearGradient](./ts-basic-components-datapanel.md#lineargradient10) and [animateTo()](./ts-explicit-animation.md).
1500
1501```ts
1502import { curves } from '@kit.ArkUI';
1503
1504@Entry
1505@Component
1506struct ImageExample11 {
1507  private curve = curves.cubicBezierCurve(0.33, 0, 0.67, 1);
1508  @State moveImg: string[] = ['imageScanEffect'];
1509  @State moveImgVisible: Visibility = Visibility.Visible;
1510  @State durationTime: number = 1500;
1511  @State iterationsTimes: number = -1;
1512  @State private opacityValue: number = 0.5;
1513  @State imageWidth: number = 450;
1514  @State visible: Visibility = Visibility.Hidden;
1515  @State stackBackgroundColor: string = '#E1E4E9';
1516  @State linePositionX: number = 0 - this.imageWidth;
1517  @State linePositionY: number = 0;
1518  @State imgResource: Resource | undefined = undefined;
1519
1520  startupAnimate() {
1521    this.moveImg.pop();
1522    this.moveImg.push('imageScanEffect');
1523    setTimeout(() => {
1524      this.imgResource = $r('app.media.img');
1525    }, 3000);
1526    this.getUIContext()?.animateTo({
1527      duration: this.durationTime,
1528      curve: this.curve,
1529      tempo: 1,
1530      iterations: this.iterationsTimes,
1531      delay: 0
1532    }, () => {
1533      this.linePositionX = this.imageWidth;
1534    })
1535  }
1536
1537  build() {
1538    Column() {
1539      Row() {
1540        Stack() {
1541          Image(this.imgResource)
1542            .width(this.imageWidth)
1543            .height(200)
1544            .objectFit(ImageFit.Contain)
1545            .visibility(this.visible)
1546            .onComplete(() => {
1547              this.visible = Visibility.Visible;
1548              this.moveImg.pop();
1549            })
1550            .onError(() =>{
1551              setTimeout(() => {
1552                this.visible = Visibility.Visible;
1553                this.moveImg.pop();
1554              }, 2600)
1555            })
1556          ForEach(this.moveImg, (item: string) => {
1557            Row()
1558              .width(this.imageWidth)
1559              .height(200)
1560              .visibility(this.moveImgVisible)
1561              .position({ x: this.linePositionX, y: this.linePositionY })
1562              .linearGradient({
1563                direction: GradientDirection.Right,
1564                repeating: false,
1565                colors: [[0xE1E4E9, 0], [0xFFFFFF, 0.75], [0xE1E4E9, 1]]
1566              })
1567              .opacity(this.opacityValue)
1568          })
1569        }
1570        .backgroundColor(this.visible ? this.stackBackgroundColor : undefined)
1571        .margin({top: 20, left: 20, right: 20})
1572        .borderRadius(20)
1573        .clip(true)
1574        .onAppear(() => {
1575          this.startupAnimate();
1576        })
1577      }
1578    }
1579  }
1580}
1581```
1582
1583![imageContent](figures/imageScanEffect.gif)
1584
1585### Example 14: Adding Transform Effects to an Image
1586
1587This example demonstrates how to apply rotation and translation effects to an image using the [imageMatrix](#imagematrix15) and [objectFit](#objectfit) attributes.
1588
1589```ts
1590import { matrix4 } from '@kit.ArkUI';
1591
1592@Entry
1593@Component
1594struct Test {
1595  private matrix1 = matrix4.identity()
1596    .translate({ x: -400, y: -750 })
1597    .scale({ x: 0.5, y: 0.5 })
1598    .rotate({
1599      x: 2,
1600      y: 0.5,
1601      z: 3,
1602      centerX: 10,
1603      centerY: 10,
1604      angle: -10
1605    })
1606
1607  build() {
1608    Row() {
1609      Column({ space: 50 }) {
1610        Column({ space: 5 }) {
1611          Image($r('app.media.example'))
1612            .border({ width:2, color: Color.Black })
1613            .objectFit(ImageFit.Contain)
1614            .width(150)
1615            .height(150)
1616          Text('No transformation')
1617            .fontSize('25px')
1618        }
1619        Column({ space: 5 }) {
1620          Image($r('app.media.example'))
1621            .border({ width:2, color: Color.Black })
1622            .objectFit(ImageFit.None)
1623            .translate({ x: 10, y: 10 })
1624            .scale({ x: 0.5, y: 0.5 })
1625            .width(100)
1626            .height(100)
1627          Text('Direct transformation on the image, with the upper left corner of the image source displayed by default')
1628            .fontSize('25px')
1629        }
1630        Column({ space: 5 }) {
1631          Image($r('app.media.example'))
1632            .objectFit(ImageFit.MATRIX)
1633            .imageMatrix(this.matrix1)
1634            .border({ width:2, color: Color.Black })
1635            .width(150)
1636            .height(150)
1637          Text('Transformation using imageMatrix to adjust the source position for optimal display')
1638            .fontSize('25px')
1639        }
1640      }
1641      .width('100%')
1642    }
1643  }
1644}
1645```
1646
1647![imageMatrix](figures/imageMatrix.jpeg)
1648
1649### Example 15: Setting the Image Decoding Size Using sourceSize
1650
1651This example uses the [sourceSize](ts-basic-components-image.md#sourcesize) API to customize the image decoding size.
1652
1653```ts
1654@Entry
1655@Component
1656struct Index {
1657  @State borderRadiusValue: number = 10;
1658  build() {
1659    Column() {
1660      Image($r('app.media.sky'))
1661        .sourceSize({width:1393, height:1080})
1662        .height(300)
1663        .width(300)
1664        .objectFit(ImageFit.Contain)
1665        .borderWidth(1)
1666      Image($r('app.media.sky'))
1667        .sourceSize({width:13, height:10})
1668        .height(300)
1669        .width(300)
1670        .objectFit(ImageFit.Contain)
1671        .borderWidth(1)
1672    }
1673    .height('100%')
1674    .width('100%')
1675  }
1676}
1677```
1678
1679![sourceSizeExample](figures/sourceSizeExample.png)
1680
1681### Example 16: Setting the Image Rendering Mode Using renderMode
1682
1683This example uses the [renderMode](ts-basic-components-image.md#rendermode) API to set the image rendering mode to grayscale.
1684
1685```ts
1686@Entry
1687@Component
1688struct Index {
1689  @State borderRadiusValue: number = 10;
1690  build() {
1691    Column() {
1692      Image($r('app.media.sky'))
1693        .renderMode(ImageRenderMode.Template)
1694        .height(300)
1695        .width(300)
1696        .objectFit(ImageFit.Contain)
1697        .borderWidth(1)
1698    }
1699    .height('100%')
1700    .width('100%')
1701  }
1702}
1703```
1704
1705![renderModeExample](figures/renderModeExample.png)
1706
1707### Example 17: Setting the Image Repeat Pattern Using objectRepeat
1708
1709This example uses the [objectRepeat](ts-basic-components-image.md#objectrepeat) API to repeat the image along the vertical axis.
1710
1711```ts
1712@Entry
1713@Component
1714struct Index {
1715  @State borderRadiusValue: number = 10;
1716  build() {
1717    Column() {
1718      Image($r('app.media.sky'))
1719        .objectRepeat(ImageRepeat.Y)
1720        .height('90%')
1721        .width('90%')
1722        .objectFit(ImageFit.Contain)
1723        .borderWidth(1)
1724    }
1725    .height('100%')
1726    .width('100%')
1727  }
1728}
1729```
1730
1731![objectRepeatExample](figures/objectRepeatExample.png)
1732
1733### Example 18: Setting the Fill Color for an SVG Image
1734
1735This example shows how to set different fill colors for an SVG image using the [fillColor](#fillcolor15) attribute.
1736
1737```ts
1738@Entry
1739@Component
1740struct Index {
1741  build() {
1742    Column() {
1743      Text('FillColor not set')
1744      Image($r('app.media.svgExample'))
1745        .height(100)
1746        .width(100)
1747        .objectFit(ImageFit.Contain)
1748        .borderWidth(1)
1749      Text('fillColor set to ColorContent.ORIGIN')
1750      Image($r('app.media.svgExample'))
1751        .height(100)
1752        .width(100)
1753        .objectFit(ImageFit.Contain)
1754        .borderWidth(1)
1755        .fillColor(ColorContent.ORIGIN)
1756      Text('fillColor set to Color.Blue')
1757      Image($r('app.media.svgExample'))
1758        .height(100)
1759        .width(100)
1760        .objectFit(ImageFit.Contain)
1761        .borderWidth(1)
1762        .fillColor(Color.Blue)
1763      Text('fillColor set to undefined')
1764      Image($r('app.media.svgExample'))
1765        .height(100)
1766        .width(100)
1767        .objectFit(ImageFit.Contain)
1768        .borderWidth(1)
1769        .fillColor(undefined)
1770    }
1771    .height('100%')
1772    .width('100%')
1773  }
1774}
1775```
1776
1777![fillColorExample](figures/fillColorExample.png)
1778
1779### Example 19: Adjusting HDR Image Brightness
1780
1781This example demonstrates how to adjust the HDR image brightness using the [hdrBrightness](#hdrbrightness19) attribute, changing the value from **0** to **1**.
1782
1783```ts
1784import { image } from '@kit.ImageKit';
1785
1786const TAG = 'AceImage';
1787
1788@Entry
1789@Component
1790struct Index {
1791  @State imgUrl: string = 'img_1';
1792  @State bright: number = 0; // The default brightness is 0.
1793  aboutToAppear(): void {
1794    // Obtain media resources from the resource manager.
1795    let img = this.getUIContext().getHostContext()?.resourceManager.getMediaByNameSync(this.imgUrl);
1796    // Create an image source and obtain image information.
1797    let imageSource = image.createImageSource(img?.buffer.slice(0));
1798    let imageInfo = imageSource.getImageInfoSync();
1799    // Check whether the image information is obtained successfully.
1800    if (imageInfo == undefined) {
1801      console.error(TAG, 'Failed to obtain the image information.');
1802    } else {
1803      // After the image information is obtained successfully, print the HDR status.
1804      console.info(TAG, 'imageInfo.isHdr:' + imageInfo.isHdr);
1805    }
1806  }
1807
1808  build() {
1809    Column() {
1810      Image($r('app.media.img_1')).width('50%')
1811        .height('auto')
1812        .margin({top:160})
1813        .hdrBrightness(this.bright) // Set the HDR image brightness controlled by the bright state.
1814      Button('Adjust Brightness 0 -> 1')
1815        .onClick(() => {
1816          // Animation transition for brightness changes
1817          this.getUIContext()?.animateTo({}, () => {
1818            this.bright = 1.0 - this.bright;
1819          });
1820        })
1821    }
1822    .height('100%')
1823    .width('100%')
1824  }
1825}
1826```
1827
1828### Example 20: Setting Whether the Image Follows the System Language Direction
1829
1830This example shows how to use the [matchTextDirection](#matchtextdirection) API to set whether the image should be mirrored when the device system language is set to Uyghur.
1831
1832```ts
1833@Entry
1834@Component
1835struct Index {
1836  build() {
1837    Column() {
1838      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
1839        Row() {
1840          // The image does not follow the system language direction.
1841          Image($r('app.media.ocean'))
1842            .width(110).height(110).margin(15)
1843            .matchTextDirection(false)
1844        }
1845        Row() {
1846          // The image follows the system language direction.
1847          Image($r('app.media.ocean'))
1848            .width(110).height(110).margin(15)
1849            .matchTextDirection(true)
1850        }
1851      }
1852    }.height(320).width(360).padding({ right: 10, top: 10 })
1853  }
1854}
1855```
1856
1857![matchTextDirection](figures/matchTextDirection.png)
1858
1859### Example 21: Setting Image Display Orientation
1860
1861This example shows how to configure different image display orientations using the [orientation](#orientation14) attribute.
1862
1863```ts
1864@Entry
1865@Component
1866struct OrientationExample {
1867  build() {
1868    Column() {
1869      Row({ space: 25 }) {
1870        Column() {
1871          Text('AUTO')
1872          Image($r('app.media.hello'))
1873            .width(125).height(125)
1874            .orientation(ImageRotateOrientation.AUTO)
1875        }
1876
1877        Column() {
1878          Text('UP')
1879          Image($r('app.media.hello'))
1880            .width(125).height(125)
1881            .orientation(ImageRotateOrientation.UP)
1882        }
1883
1884        Column() {
1885          Text('RIGHT')
1886          Image($r('app.media.hello'))
1887            .width(125).height(125)
1888            .orientation(ImageRotateOrientation.RIGHT)
1889        }
1890      }
1891
1892      Row({ space: 25 }) {
1893        Column() {
1894          Text('DOWN')
1895          Image($r('app.media.hello'))
1896            .width(125).height(125)
1897            .orientation(ImageRotateOrientation.DOWN)
1898        }
1899
1900        Column() {
1901          Text('LEFT')
1902          Image($r('app.media.hello'))
1903            .width(125).height(125)
1904            .orientation(ImageRotateOrientation.LEFT)
1905        }
1906
1907        Column() {
1908          Text('UP_MIRRORED')
1909          Image($r('app.media.hello'))
1910            .width(125).height(125)
1911            .orientation(ImageRotateOrientation.UP_MIRRORED)
1912        }
1913      }
1914
1915      Row({ space: 15 }) {
1916        Column() {
1917          Text('RIGHT_MIRRORED')
1918          Image($r('app.media.hello'))
1919            .width(125).height(125)
1920            .orientation(ImageRotateOrientation.RIGHT_MIRRORED)
1921        }
1922
1923        Column() {
1924          Text('DOWN_MIRRORED')
1925          Image($r('app.media.hello'))
1926            .width(125).height(125)
1927            .orientation(ImageRotateOrientation.DOWN_MIRRORED)
1928        }
1929
1930        Column() {
1931          Text('LEFT_MIRRORED')
1932          Image($r('app.media.hello'))
1933            .width(125).height(125)
1934            .orientation(ImageRotateOrientation.LEFT_MIRRORED)
1935        }
1936      }
1937    }
1938  }
1939}
1940```
1941
1942![orientation](figures/orientation.png)
1943
1944### Example 22: Using EXIF Metadata for Image Display Orientation
1945
1946This example demonstrates how to use the [getImageProperty](../../apis-image-kit/arkts-apis-image-ImageSource.md#getimageproperty11) API to obtain the EXIF metadata of an image, and then set the image display orientation through the [orientation](#orientation14) attribute based on the obtained EXIF metadata.
1947
1948```ts
1949import { image } from '@kit.ImageKit';
1950import { resourceManager } from '@kit.LocalizationKit';
1951
1952@Entry
1953@Component
1954struct Example {
1955  @State rotateOrientation: ImageRotateOrientation = ImageRotateOrientation.UP;
1956  @State pixelMap: image.PixelMap | undefined = undefined;
1957  @State text1: string = 'The exif orientation is ';
1958  @State text2: string = 'Set orientation to ';
1959
1960  // Convert EXIF orientation information into ImageRotateOrientation.
1961  getOrientation(orientation: string): ImageRotateOrientation {
1962    if (orientation == 'Top-right') {
1963      this.text2 = this.text2 + 'UP_MIRRORED';
1964      return ImageRotateOrientation.UP_MIRRORED;
1965    } else if (orientation == 'Bottom-right') {
1966      this.text2 = this.text2 + 'DOWN';
1967      return ImageRotateOrientation.DOWN;
1968    } else if (orientation == 'Bottom-left') {
1969      this.text2 = this.text2 + 'DOWN_MIRRORED';
1970      return ImageRotateOrientation.DOWN_MIRRORED;
1971    } else if (orientation == 'Left-top') {
1972      this.text2 = this.text2 + 'LEFT_MIRRORED';
1973      return ImageRotateOrientation.LEFT_MIRRORED;
1974    } else if (orientation == 'Right-top') {
1975      this.text2 = this.text2 + 'RIGHT';
1976      return ImageRotateOrientation.RIGHT;
1977    } else if (orientation == 'Right-bottom') {
1978      this.text2 = this.text2 + 'RIGHT_MIRRORED';
1979      return ImageRotateOrientation.RIGHT_MIRRORED;
1980    } else if (orientation == 'Left-bottom') {
1981      this.text2 = this.text2 + 'LEFT';
1982      return ImageRotateOrientation.LEFT;
1983    } else if (orientation == 'Top-left') {
1984      this.text2 = this.text2 + 'UP';
1985      return ImageRotateOrientation.UP;
1986    } else {
1987      this.text2 = this.text2 + 'UP';
1988      return ImageRotateOrientation.UP;
1989    }
1990  }
1991
1992  async getFileBuffer(context: Context): Promise<ArrayBuffer | undefined> {
1993    try {
1994      const resourceMgr: resourceManager.ResourceManager = context.resourceManager;
1995      // Obtain the content of the resource file with EXIF data as Uint8Array.
1996      const fileData: Uint8Array = await resourceMgr.getRawFileContent('hello.jpg');
1997      console.info('Successfully get RawFileContent');
1998      // Convert the array to an ArrayBuffer and return the ArrayBuffer.
1999      const buffer: ArrayBuffer = fileData.buffer.slice(0);
2000      return buffer;
2001    } catch (error) {
2002      console.error('Failed to get RawFileContent');
2003      return undefined;
2004    }
2005  }
2006
2007  aboutToAppear() {
2008    let context = this.getUIContext().getHostContext();
2009    if (!context) {
2010      return;
2011    }
2012    this.getFileBuffer(context).then((buf: ArrayBuffer | undefined) => {
2013      let imageSource = image.createImageSource(buf);
2014      if (!imageSource) {
2015        return;
2016      }
2017      // Obtain EXIF orientation information.
2018      imageSource.getImageProperty(image.PropertyKey.ORIENTATION).then((orientation) => {
2019        this.rotateOrientation = this.getOrientation(orientation);
2020        this.text1 = this.text1 + orientation;
2021        let options: image.DecodingOptions = {
2022          'editable': true,
2023          'desiredPixelFormat': image.PixelMapFormat.RGBA_8888,
2024        }
2025        imageSource.createPixelMap(options).then((pixelMap: image.PixelMap) => {
2026          this.pixelMap = pixelMap;
2027          imageSource.release();
2028        });
2029      }).catch(() => {
2030        imageSource.release();
2031      });
2032    })
2033  }
2034
2035  build() {
2036    Column({ space: 40 }) {
2037      Column({ space: 10 }) {
2038        Text('before').fontSize(20).fontWeight(700)
2039        Image($rawfile('hello.jpg'))
2040          .width(100)
2041          .height(100)
2042        Text(this.text1)
2043      }
2044
2045      Column({ space: 10 }) {
2046        Text('after').fontSize(20).fontWeight(700)
2047        Image(this.pixelMap)
2048          .width(100)
2049          .height(100)
2050          .orientation(this.rotateOrientation)
2051        Text(this.text2)
2052      }
2053    }
2054    .height('80%')
2055    .width('100%')
2056  }
2057}
2058```
2059
2060![orientation2](figures/orientation2.png)
2061
2062### Example 23: Dynamically Switching an SVG Image Between Fill Colors
2063
2064This example demonstrates how to dynamically switch an SVG Image between fill colors across different color spaces using [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12).
2065
2066```ts
2067import { ColorMetrics } from '@kit.ArkUI';
2068@Entry
2069@Component
2070struct fillColorMetricsDemo {
2071  @State p3Red: ColorMetrics = ColorMetrics.colorWithSpace(ColorSpace.DISPLAY_P3, 0.631, 0.0392, 0.1294);
2072  @State sRGBRed: ColorMetrics = ColorMetrics.colorWithSpace(ColorSpace.SRGB, 0.631, 0.0392, 0.1294);
2073  @State p3Green: ColorMetrics = ColorMetrics.colorWithSpace(ColorSpace.DISPLAY_P3, 0.09, 0.662 ,0.552);
2074  @State sRGBGreen: ColorMetrics = ColorMetrics.colorWithSpace(ColorSpace.SRGB, 0.09, 0.662 ,0.552);
2075  @State p3Blue: ColorMetrics = ColorMetrics.colorWithSpace(ColorSpace.DISPLAY_P3, 0, 0.290 ,0.686);
2076  @State sRGBBlue: ColorMetrics = ColorMetrics.colorWithSpace(ColorSpace.SRGB, 0, 0.290 ,0.686);
2077  @State colorArray: (Color|undefined|ColorMetrics|ColorContent)[] = [
2078    this.p3Red, this.sRGBRed, this.p3Green, this.sRGBGreen, this.p3Blue,
2079    this.sRGBBlue, ColorContent.ORIGIN, Color.Gray, undefined
2080  ]
2081  @State colorArrayStr: string[] = [
2082    "P3 Red", "SRGB Red", "P3 Green", "SRGB Green",
2083    "P3 Blue", "SRGB Blue", "ORIGIN", "Gray", "undefined"
2084  ]
2085  @State arrayIdx: number = 0
2086  build() {
2087    Column() {
2088      Text("FillColor is " + this.colorArrayStr[this.arrayIdx])
2089      Image($r('app.media.svgExample'))
2090        .width(110).height(110).margin(15)
2091        .fillColor(this.colorArray[this.arrayIdx])
2092      Button("ChangeFillColor")
2093        .onClick(()=>{
2094          this.arrayIdx = (this.arrayIdx + 1) % this.colorArray.length
2095        })
2096      Blank().height(30).width('100%')
2097      Text("FillColor is SRGB Red")
2098      Image($r('app.media.svgExample'))
2099        .width(110).height(110).margin(15)
2100        .fillColor(this.sRGBRed)
2101      Blank().height(30).width('100%')
2102      Text("FillColor is SRGB Green")
2103      Image($r('app.media.svgExample'))
2104        .width(110).height(110).margin(15)
2105        .fillColor(this.sRGBGreen)
2106      Blank().height(30).width('100%')
2107      Text("FillColor is SRGB Blue")
2108      Image($r('app.media.svgExample'))
2109        .width(110).height(110).margin(15)
2110        .fillColor(this.sRGBBlue)
2111    }
2112  }
2113}
2114```
2115
2116![colorMetrics](figures/colorMetrics.gif)
2117<!--no_check-->