1# Image
2
3The **Image** component is usually used to display images in applications. It supports images in PNG, JPG, JPEG, BMP, SVG, WEBP, GIF, or HEIF format from the following data sources: [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7), [ResourceStr](ts-types.md#resourcestr), or [DrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#drawabledescriptor).
4
5> **NOTE**
6>
7> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
8>
9> 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, the animation stops when the **Image** component is invisible. The component's visibility is determined by the value of **ratios** in the [onVisibleAreaChange](./ts-universal-component-visible-area-change-event.md#onvisibleareachange) event callback: If the value is greater than 0, the component is visible.
14
15## Required Permissions
16
17The **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).
18
19
20## Child Components
21
22Not supported
23
24
25## APIs
26
27### Image
28
29Image(src: PixelMap | ResourceStr | DrawableDescriptor)
30
31Obtains an image from the specified source for subsequent rendering and display.
32
33If 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.
34
35By 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.
36
37If 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.
38
39**Widget capability**: This API can be used in ArkTS widgets since API version 9.
40
41**Atomic service API**: This API can be used in atomic services since API version 11.
42
43**System capability**: SystemCapability.ArkUI.ArkUI.Full
44
45**Parameters**
46
47| Name | Type                                    | Mandatory  | Description                                    |
48| ---- | ---------------------------------------- | ---- | ---------------------------------------- |
49| src  | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) \| [ResourceStr](ts-types.md#resourcestr)\| [DrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#drawabledescriptor) | Yes   | Data source of the image. Local and online sources are supported. For details about how to reference an image, see [Loading Image Resources](../../../ui/arkts-graphics-display.md#loading-image-resources).<br>1. **PixelMap**: an array of pixels storing graphical information. This type is usually used in image editing scenarios.<br>2. **ResourceStr**: a string or a **Resource** object.<br>The string format can be used to load local images and, more frequently, online images. When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **Image** component cannot be called across bundles or modules. If an image needs to be used globally, you are advised to use the **Resource** format. The following types of strings are supported:<br>- Base64 strings in the format of data:image/[png\|jpeg\|bmp\|webp\|heif];base64,[base64 data], where *[base64 data]* is a Base64 string.<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.<br>- ArkTS widgets do not support the [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) type.<br>- When a local image is being loaded, any modification or replacement of it may cause application crash. Therefore, to overwrite an image file, delete the file first and then create one with the same name.<br>- Online images must support the RFC 9113 standard to be successfully loaded.<br>- If images to download are greater than 10 MB or in large number, consider using [HTTP](../../../network/http-request.md) to preload them to improve the image loading performance and facilitate data management on the application side.<br> - Directly passing a URL to the **Image** component can lead to potential performance issues, such as: (1) Large images cannot be preloaded, resulting in longer display times for white blocks; (2) Small images set to load synchronously can block the UI thread in weak network environments, causing screen freezing issues; (3) In fast-scrolling water flow layouts, images that are about to be displayed could not be preloaded, leading to more white blocks during scrolling. Performance issues manifest differently in different scenarios. To address these issues, decouple the network downloading part from the display of the **Image** component, which allows for preloading or asynchronous downloading.<br>- To display an SVG image that does not have the native size, you must set the width and height for the **Image** component.<br>- If an SVG image references another local image through the Image tag, the referenced image cannot be in .svg or .gif format.<br>- When the **src** attribute changes from a valid value to an invalid one, the image remains unchanged.<br>- If this parameter is of the [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) 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.|
50
51### Image<sup>12+</sup>
52
53Image(src: PixelMap | ResourceStr | DrawableDescriptor | ImageContent)
54
55Obtains an image. The [ImageContent](#imagecontent12) type allows you to specify the image content.
56
57**Widget capability**: This API can be used in ArkTS widgets since API version 12.
58
59**Atomic service API**: This API can be used in atomic services since API version 12.
60
61**System capability**: SystemCapability.ArkUI.ArkUI.Full
62
63**Parameters**
64
65| Name | Type                                    | Mandatory  | Description                                    |
66| ---- | ---------------------------------------- | ---- | ---------------------------------------- |
67| src  | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) \| [ResourceStr](ts-types.md#resourcestr)\| [DrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#drawabledescriptor)\| [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>1. **PixelMap**: an array of pixels storing graphical information. This type is usually used in image editing scenarios.<br>2. **ResourceStr**: a string or a **Resource** object.<br>The string format can be used to load local images and, more frequently, online images. When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **Image** component cannot be called across bundles or modules. If an image needs to be used globally, you are advised to use the **Resource** format. The following types of strings are supported:<br>- Base64 strings in the format of data:image/[png\|jpeg\|bmp\|webp\|heif];base64,[base64 data], where *[base64 data]* is a Base64 string.<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>4. [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.<br>- ArkTS widgets do not support the [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) type.<br>- When a local image is being loaded, any modification or replacement of it may cause application crash. Therefore, to overwrite an image file, delete the file first and then create one with the same name.<br>- Online images must support the RFC 9113 standard to be successfully loaded.<br>- If images to download are greater than 10 MB or in large number, consider using [HTTP](../../../network/http-request.md) to preload them to improve the image loading performance and facilitate data management on the application side.<br> - Directly passing a URL to the **Image** component can lead to potential performance issues, such as: (1) Large images cannot be preloaded, resulting in longer display times for white blocks; (2) Small images set to load synchronously can block the UI thread in weak network environments, causing screen freezing issues; (3) In fast-scrolling water flow layouts, images that are about to be displayed could not be preloaded, leading to more white blocks during scrolling. Performance issues manifest differently in different scenarios. To address these issues, decouple the network downloading part from the display of the **Image** component, which allows for preloading or asynchronous downloading.<br>- To display an SVG image that does not have the native size, you must set the width and height for the **Image** component.<br>- If an SVG image references another local image through the Image tag, the referenced image cannot be in .svg or .gif format.<br>- When the **src** attribute changes from a valid value to an invalid one, the image remains unchanged.<br>- If this parameter is of the [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) 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.|
68
69### Image<sup>12+</sup>
70
71Image(src: PixelMap | ResourceStr | DrawableDescriptor, imageAIOptions: ImageAIOptions)
72
73Obtains an image. The [imageAIOptions](ts-image-common.md#imageaioptions) parameter allows you to set AI image analysis options.
74
75**Atomic service API**: This API can be used in atomic services since API version 12.
76
77**System capability**: SystemCapability.ArkUI.ArkUI.Full
78
79**Parameters**
80
81| Name | Type                                    | Mandatory  | Description                                    |
82| ---- | ---------------------------------------- | ---- | ---------------------------------------- |
83| src  | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) \| [ResourceStr](ts-types.md#resourcestr)\| [DrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#drawabledescriptor) | Yes   | Data source of the image. Local and online sources are supported. For details about how to reference an image, see [Loading Image Resources](../../../ui/arkts-graphics-display.md#loading-image-resources).<br>1. **PixelMap**: an array of pixels storing graphical information. This type is usually used in image editing scenarios.<br>2. **ResourceStr**: a string or a **Resource** object.<br>The string format can be used to load local images and, more frequently, online images. When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **Image** component cannot be called across bundles or modules. If an image needs to be used globally, you are advised to use the **Resource** format. The following types of strings are supported:<br>- Base64 strings in the format of data:image/[png\|jpeg\|bmp\|webp\|heif];base64,[base64 data], where *[base64 data]* is a Base64 string.<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.<br>- ArkTS widgets do not support the [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) type.<br>- When a local image is being loaded, any modification or replacement of it may cause application crash. Therefore, to overwrite an image file, delete the file first and then create one with the same name.<br>- Online images must support the RFC 9113 standard to be successfully loaded.<br>- If images to download are greater than 10 MB or in large number, consider using [HTTP](../../../network/http-request.md) to preload them to improve the image loading performance and facilitate data management on the application side.<br> - Directly passing a URL to the **Image** component can lead to potential performance issues, such as: (1) Large images cannot be preloaded, resulting in longer display times for white blocks; (2) Small images set to load synchronously can block the UI thread in weak network environments, causing screen freezing issues; (3) In fast-scrolling water flow layouts, images that are about to be displayed could not be preloaded, leading to more white blocks during scrolling. Performance issues manifest differently in different scenarios. To address these issues, decouple the network downloading part from the display of the **Image** component, which allows for preloading or asynchronous downloading.<br>- To display an SVG image that does not have the native size, you must set the width and height for the **Image** component.<br>- If an SVG image references another local image through the Image tag, the referenced image cannot be in .svg or .gif format.<br>- When the **src** attribute changes from a valid value to an invalid one, the image remains unchanged.<br>- If this parameter is of the [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) 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.|
84| 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.|
85
86## Attributes
87
88For details about how to use the attributes, see [Setting Attributes](../../../ui/arkts-graphics-display.md#setting-attributes). In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
89
90> **NOTE**
91>
92> 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.
93
94### alt
95
96alt(value: string | Resource  | PixelMap)
97
98Sets the placeholder image displayed during loading.
99
100This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
101
102**Widget capability**: This API can be used in ArkTS widgets since API version 9.
103
104**Atomic service API**: This API can be used in atomic services since API version 11.
105
106**System capability**: SystemCapability.ArkUI.ArkUI.Full
107
108**Parameters**
109
110| Name| Type                                                    | Mandatory| Description                                                        |
111| ------ | -------------------------------------------------------- | ---- | ------------------------------------------------------------ |
112| value  | string \| [Resource](ts-types.md#resource) \| [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7)<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/js-apis-image.md#pixelmap7) objects are supported, but online images are not.<br>Default value: **null**|
113
114### objectFit
115
116objectFit(value: ImageFit)
117
118Sets how the image is resized to fit its container.
119
120**Widget capability**: This API can be used in ArkTS widgets since API version 9.
121
122**Atomic service API**: This API can be used in atomic services since API version 11.
123
124**System capability**: SystemCapability.ArkUI.ArkUI.Full
125
126**Parameters**
127
128| Name| Type                                     | Mandatory| Description                                       |
129| ------ | ----------------------------------------- | ---- | ------------------------------------------- |
130| value  | [ImageFit](ts-appendix-enums.md#imagefit) | Yes  | How the image is resized to fit its container.<br>Default value: **ImageFit.Cover**|
131
132### objectRepeat
133
134objectRepeat(value: ImageRepeat)
135
136Sets 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.
137
138This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
139
140**Widget capability**: This API can be used in ArkTS widgets since API version 9.
141
142**Atomic service API**: This API can be used in atomic services since API version 11.
143
144**System capability**: SystemCapability.ArkUI.ArkUI.Full
145
146**Parameters**
147
148| Name| Type                                           | Mandatory| Description                                             |
149| ------ | ----------------------------------------------- | ---- | ------------------------------------------------- |
150| value  | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Yes  | How the image is repeated.<br>Default value: **ImageRepeat.NoRepeat**|
151
152### interpolation
153
154interpolation(value: ImageInterpolation)
155
156Sets 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.
157
158This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
159
160**Widget capability**: This API can be used in ArkTS widgets since API version 9.
161
162**Atomic service API**: This API can be used in atomic services since API version 11.
163
164**System capability**: SystemCapability.ArkUI.ArkUI.Full
165
166**Parameters**
167
168| Name| Type                                     | Mandatory| Description                                               |
169| ------ | ----------------------------------------- | ---- | --------------------------------------------------- |
170| value  | [ImageInterpolation](#imageinterpolation) | Yes  | Interpolation effect of the image.<br>Default value: **ImageInterpolation.Low**|
171
172### renderMode
173
174renderMode(value: ImageRenderMode)
175
176Sets the rendering mode of the image. This attribute is not applicable to SVG images.
177
178When [ColorFilter](#colorfilter9) is set, this attribute is not effective.
179
180This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
181
182**Widget capability**: This API can be used in ArkTS widgets since API version 9.
183
184**Atomic service API**: This API can be used in atomic services since API version 11.
185
186**System capability**: SystemCapability.ArkUI.ArkUI.Full
187
188**Parameters**
189
190| Name| Type                               | Mandatory| Description                                                        |
191| ------ | ----------------------------------- | ---- | ------------------------------------------------------------ |
192| value  | [ImageRenderMode](#imagerendermode) | Yes  | Rendering mode of the image, which can be **Original** or **Template** (monochrome).<br>Default value: **ImageRenderMode.Original**|
193
194### sourceSize
195
196sourceSize(value: ImageSourceSize)
197
198Sets 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.
199
200This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
201
202**Widget capability**: This API can be used in ArkTS widgets since API version 9.
203
204**Atomic service API**: This API can be used in atomic services since API version 11.
205
206**System capability**: SystemCapability.ArkUI.ArkUI.Full
207
208**Parameters**
209
210| Name| Type                                                   | Mandatory| Description                                                        |
211| ------ | ------------------------------------------------------- | ---- | ------------------------------------------------------------ |
212| value  | [ImageSourceSize](#imagesourcesize14) | 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.|
213
214### matchTextDirection
215
216matchTextDirection(value: boolean)
217
218Specifies whether to display the image in the system language direction. When **value** is set to **true**, the image is horizontally flipped in the right-to-left (RTL) language context.
219
220This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
221
222**Widget capability**: This API can be used in ArkTS widgets since API version 9.
223
224**Atomic service API**: This API can be used in atomic services since API version 11.
225
226**System capability**: SystemCapability.ArkUI.ArkUI.Full
227
228**Parameters**
229
230| Name| Type   | Mandatory| Description                                        |
231| ------ | ------- | ---- | -------------------------------------------- |
232| value  | boolean | Yes  | Whether to display the image in the system language direction.<br>Default value: **false**|
233
234### fitOriginalSize
235
236fitOriginalSize(value: boolean)
237
238Specifies whether to fit the component to the size of the image source when the component size is not set.
239
240This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
241
242**Widget capability**: This API can be used in ArkTS widgets since API version 9.
243
244**Atomic service API**: This API can be used in atomic services since API version 11.
245
246**System capability**: SystemCapability.ArkUI.ArkUI.Full
247
248**Parameters**
249
250| Name| Type   | Mandatory| Description                                            |
251| ------ | ------- | ---- | ------------------------------------------------ |
252| value  | boolean | Yes  | Whether to fit the image to the size of the image source.<br>Default value: **false**<br>**NOTE**<br>If **fitOriginalSize** is set to **false** or is not set, the component does not fit the image to the size of the image source.<br> If **fitOriginalSize** is set to true, the component fits the image to the size of the image source.|
253
254### fillColor
255
256fillColor(value: ResourceColor)
257
258Sets 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).
259
260This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
261
262**Widget capability**: This API can be used in ArkTS widgets since API version 9.
263
264**Atomic service API**: This API can be used in atomic services since API version 11.
265
266**System capability**: SystemCapability.ArkUI.ArkUI.Full
267
268**Parameters**
269
270| Name| Type                                      | Mandatory| Description          |
271| ------ | ------------------------------------------ | ---- | -------------- |
272| value  | [ResourceColor](ts-types.md#resourcecolor) | Yes  | Fill color to be superimposed on the image.|
273
274### autoResize
275
276autoResize(value: boolean)
277
278Specifies 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.
279
280If the original image size does not match the display size, the image may be distorted or blurred. Recommended configuration for the optimal definition:
281
282When the image is scaled down: .autoResize(false) + .interpolation(.Medium)
283
284When the image is scaled up: .interpolation(.High)
285
286This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
287
288**Widget capability**: This API can be used in ArkTS widgets since API version 9.
289
290**Atomic service API**: This API can be used in atomic services since API version 11.
291
292**System capability**: SystemCapability.ArkUI.ArkUI.Full
293
294**Parameters**
295
296| Name| Type   | Mandatory| Description                                                        |
297| ------ | ------- | ---- | ------------------------------------------------------------ |
298| 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**|
299
300### syncLoad<sup>8+</sup>
301
302syncLoad(value: boolean)
303
304Specifies 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.
305
306This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
307
308**Widget capability**: This API can be used in ArkTS widgets since API version 9.
309
310**Atomic service API**: This API can be used in atomic services since API version 11.
311
312**System capability**: SystemCapability.ArkUI.ArkUI.Full
313
314**Parameters**
315
316| Name| Type   | Mandatory| Description                                                        |
317| ------ | ------- | ---- | ------------------------------------------------------------ |
318| 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**|
319
320### copyOption<sup>9+</sup>
321
322copyOption(value: CopyOptions)
323
324Whether 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.
325
326This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
327
328**Widget capability**: This API can be used in ArkTS widgets since API version 9.
329
330**Atomic service API**: This API can be used in atomic services since API version 11.
331
332**System capability**: SystemCapability.ArkUI.ArkUI.Full
333
334**Parameters**
335
336| Name| Type                                            | Mandatory| Description                                         |
337| ------ | ------------------------------------------------ | ---- | --------------------------------------------- |
338| value  | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Yes  | Specifies whether the image can be copied.<br>Default value: **CopyOptions.None**|
339
340### colorFilter<sup>9+</sup>
341
342colorFilter(value: ColorFilter | DrawingColorFilter)
343
344Sets the color filter for the image.
345
346When this attribute is set, [renderMode](#rendermode) is not effective.
347
348**Widget capability**: This API can be used in ArkTS widgets since API version 9.
349
350**Atomic service API**: This API can be used in atomic services since API version 11.
351
352**System capability**: SystemCapability.ArkUI.ArkUI.Full
353
354**Parameters**
355
356| Name| Type                                   | Mandatory| Description                                                        |
357| ------ | --------------------------------------- | ---- | ------------------------------------------------------------ |
358| value  | [ColorFilter](ts-types.md#colorfilter9) \| [DrawingColorFilter](../../apis-arkgraphics2d/js-apis-graphics-drawing.md#colorfilter)<sup>12+</sup> | 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 a vector value of R (red), the second row represents a vector value of G (green), the third row represents a vector value of B (blue), and the fourth row represents a vector value of A (alpha). The four rows represent different RGBA vector values.<br>If the matrix contains entries of 1 on the diagonal and entries of 0 in other places, the original color of the image is retained.<br> **Calculation rule:**<br>If the input filter matrix is as follows:<br>![image-matrix-1](figures/image-matrix-1.jpg)<br>Wherein the color is [R, G, B, A].<br>Then the color after filtering is [R', G', B', A'].<br>![image-matrix-2](figures/image-matrix-2.jpg)<br>2. The ColorFilter type of **@ohos.graphics.drawing** can be used as the 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. The SVG image to set as the source must have the **stroke** attribute.|
359
360### draggable<sup>9+</sup>
361
362draggable(value: boolean)
363
364Specifies whether the image is draggable. This attribute cannot be used together with the [onDragStart](ts-universal-events-drag-drop.md#ondragstart) event.
365
366**Atomic service API**: This API can be used in atomic services since API version 11.
367
368**System capability**: SystemCapability.ArkUI.ArkUI.Full
369
370**Parameters**
371
372| Name| Type   | Mandatory| Description                                                        |
373| ------ | ------- | ---- | ------------------------------------------------------------ |
374| 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**.|
375
376### enableAnalyzer<sup>11+</sup>
377
378enableAnalyzer(enable: boolean)
379
380Sets whether to enable the AI analyzer, which supports subject recognition, text recognition, and object lookup.<!--RP3--><!--RP3End-->
381
382This 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.
383
384Images to be analyzed must be static, non-vector images. That is, SVG and GIF images cannot be analyzed. [Pixel maps](../../apis-image-kit/js-apis-image.md#pixelmap7) in [RGBA_8888](../../apis-image-kit/js-apis-image.md#pixelmapformat7) format can be passed in for analysis. For details, see [Example 4](#example-4-enabling-the-ai-analyzer).
385
386The 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.
387
388Analysis 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 analyzer.
389
390This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
391
392> **NOTE**
393>
394> The ohos.permission.INTERNET permission must be declared.
395
396**Atomic service API**: This API can be used in atomic services since API version 12.
397
398**System capability**: SystemCapability.ArkUI.ArkUI.Full
399
400**Parameters**
401
402| Name| Type   | Mandatory| Description                                                        |
403| ------ | ------- | ---- | ------------------------------------------------------------ |
404| enable  | boolean | Yes  | Whether to enable the AI analyzer. The value **true** means to enable the AI analyzer.<br>Default value: **false**|
405
406### resizable<sup>11+</sup>
407
408resizable(value: ResizableOptions)
409
410Sets the resizable image options. Resizing is effective for drag previews and placeholder images.
411
412When [ResizableOptions](#resizableoptions11) is set to a valid value, the **objectRepeat** attribute does not take effect.
413
414When 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.
415
416This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
417
418**Atomic service API**: This API can be used in atomic services since API version 12.
419
420**System capability**: SystemCapability.ArkUI.ArkUI.Full
421
422**Parameters**
423
424| Name| Type                                   | Mandatory| Description                            |
425| ------ | --------------------------------------- | ---- | -------------------------------- |
426| value  | [ResizableOptions](#resizableoptions11) | Yes  | Resizable image options.|
427
428### privacySensitive<sup>12+</sup>
429
430privacySensitive(supported: boolean)
431
432Sets whether to secure sensitive information on widgets.
433
434**Widget capability**: This API can be used in ArkTS widgets since API version 12.
435
436**Atomic service API**: This API can be used in atomic services since API version 12.
437
438**System capability**: SystemCapability.ArkUI.ArkUI.Full
439
440**Parameters**
441
442| Name   | Type   | Mandatory| Description                    |
443| --------- | ------- | ---- | ------------------------ |
444| supported | boolean | Yes  | Whether to secure sensitive information on widgets.<br>Default value: **false**.<br>If this parameter is set to **true**, the image is obscured with a translucent background.<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).|
445
446### dynamicRangeMode<sup>12+</sup>
447
448dynamicRangeMode(value: DynamicRangeMode)
449
450Sets the dynamic range of the image to be displayed.
451
452<!--RP1--><!--RP1End-->
453
454**Atomic service API**: This API can be used in atomic services since API version 12.
455
456**System capability**: SystemCapability.ArkUI.ArkUI.Full
457
458**Parameters**
459
460| Name| Type                                   | Mandatory| Description                            |
461| ------ | --------------------------------------- | ---- | -------------------------------- |
462| value  | [DynamicRangeMode](#dynamicrangemode12-1) | Yes  | Dynamic range of the image.<br>Default value: **dynamicRangeMode.Standard**|
463
464## ImageContent<sup>12+</sup>
465
466Defines the image content.
467
468**Widget capability**: This API can be used in ArkTS widgets since API version 12.
469
470**Atomic service API**: This API can be used in atomic services since API version 12.
471
472**System capability**: SystemCapability.ArkUI.ArkUI.Full
473
474| Name    | Description                   |
475| ------ | -------------------------- |
476| EMPTY   | Empty image.                  |
477
478## ImageInterpolation
479
480**Widget capability**: This API can be used in ArkTS widgets since API version 9.
481
482**Atomic service API**: This API can be used in atomic services since API version 11.
483
484**System capability**: SystemCapability.ArkUI.ArkUI.Full
485
486| Name    | Description                      |
487| ------ | -------------------------- |
488| None   | Nearest neighbor interpolation.                  |
489| High   | Cubic interpolation. This mode produces scaled images of the highest possible quality, but may require more image rendering time.|
490| Medium | MipMap interpolation.                    |
491| Low    | Bilinear interpolation.                    |
492
493## ImageRenderMode
494
495**Widget capability**: This API can be used in ArkTS widgets since API version 9.
496
497**Atomic service API**: This API can be used in atomic services since API version 11.
498
499**System capability**: SystemCapability.ArkUI.ArkUI.Full
500
501| Name    | Description          |
502| -------- | -------------- |
503| Original | Render image pixels as they are in the original source image.|
504| Template | Render image pixels to create a monochrome template image.|
505
506## ResizableOptions<sup>11+</sup>
507
508Defines the resizable image options.
509
510**Atomic service API**: This API can be used in atomic services since API version 12.
511
512**System capability**: SystemCapability.ArkUI.ArkUI.Full
513
514| Name| Type| Mandatory| Description|
515| --------- |-----------|-----------|-----------|
516| 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.|
517| lattice<sup>12+</sup> | [DrawingLattice](../../apis-arkgraphics2d/js-apis-graphics-drawing.md#lattice12) |  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.|
518
519## EdgeWidths
520
521**Atomic service API**: This API can be used in atomic services since API version 11.
522
523**System capability**: SystemCapability.ArkUI.ArkUI.Full
524
525| Name| Type| Mandatory| Description|
526| --------- |-----------|-----------|-----------|
527|  top    |  [Length](ts-types.md#length)  |  No | Width of the top edge.<br>Default value: **0**<br>Unit: vp|
528|  right  |  [Length](ts-types.md#length)  |  No | Width of the right edge.<br>Default value: **0**<br>Unit: vp|
529|  bottom |  [Length](ts-types.md#length)  |  No | Width of the bottom edge.<br>Default value: **0**<br>Unit: vp|
530|  left   |  [Length](ts-types.md#length)  |  No | Width of the left edge.<br>Default value: **0**<br>Unit: vp|
531
532![edgewidths](figures/edgewidths.png)
533
534## DynamicRangeMode<sup>12+</sup>
535
536Describes the dynamic range of the image to be displayed.
537
538**Atomic service API**: This API can be used in atomic services since API version 12.
539
540**System capability**: SystemCapability.ArkUI.ArkUI.Full
541
542| Name    | Value   | Description                   |
543| ------ | -------------------------- | -------------------------- |
544| HIGH   | 0  | Unrestricted dynamic range, which allows for the maximum brightening of an image.             |
545| CONSTRAINT | 1 | Restricted dynamic range, which brightens an image within certain constraints.         |
546| STANDARD | 2 | Standard dynamic range, which does not brighten an image.        |
547
548## ImageSourceSize<sup>14+</sup>
549
550**Widget capability**: This API can be used in ArkTS widgets since API version 14.
551
552**Atomic service API**: This API can be used in atomic services since API version 14.
553
554**System capability**: SystemCapability.ArkUI.ArkUI.Full
555
556| Name| Type      | Mandatory| Description          |
557| ------ | --------- | ---- | ------------- |
558| width  | number | Yes  | Decoded width of the image.<br>Unit: vp|
559| height  | number | Yes  | Decoded height of the image.<br>Unit: vp|
560
561## Events
562
563In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
564
565### onComplete
566
567onComplete(callback: (event?: { width: number, height: number, componentWidth: number, componentHeight: number, loadingStatus: number,contentWidth: number, contentHeight: number, contentOffsetX: number, contentOffsetY: number }) =&gt; void)
568
569Triggered when an image is successfully loaded or decoded. The size of the loaded image is returned.
570
571This event is not triggered if the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
572
573**Widget capability**: This API can be used in ArkTS widgets since API version 9.
574
575**Atomic service API**: This API can be used in atomic services since API version 11.
576
577**System capability**: SystemCapability.ArkUI.ArkUI.Full
578
579**Parameters**
580
581| Name                      | Type  | Mandatory| Description                                                        |
582| ---------------------------- | ------ | ---- | ------------------------------------------------------------ |
583| width                        | number | Yes  | Width of the image.<br>Unit: pixel                                   |
584| height                       | number | Yes  | Height of the image.<br>Unit: pixel                                   |
585| componentWidth               | number | Yes  | Width of the component.<br>Unit: pixel                                   |
586| componentHeight              | number | Yes  | Height of the component.<br>Unit: pixel                                   |
587| 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.|
588| 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**.|
589| 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**.|
590| 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**.|
591| 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**.|
592
593### onError<sup>9+</sup>
594
595onError(callback: ImageErrorCallback)
596
597Triggered when an error occurs during image loading.
598
599This event is not triggered if the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
600
601**Widget capability**: This API can be used in ArkTS widgets since API version 9.
602
603**Atomic service API**: This API can be used in atomic services since API version 11.
604
605**System capability**: SystemCapability.ArkUI.ArkUI.Full
606
607**Parameters**
608
609| Name  | Type                                      | Mandatory| Description                      |
610| -------- | ------------------------------------------ | ---- | -------------------------- |
611| callback | [ImageErrorCallback](#imageerrorcallback9) | Yes  | Callback triggered when an error occurs during image loading.<br>**NOTE**<br> - You are advised to use this callback to quickly identify the specific causes for image loading failures.|
612
613### onFinish
614
615onFinish(event: () =&gt; void)
616
617Triggered when the animation playback in the loaded SVG image is complete. If the animation is an infinite loop, this callback is not triggered.
618
619Only SVG images are supported. This event is not triggered if the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
620
621**Widget capability**: This API can be used in ArkTS widgets since API version 9.
622
623**Atomic service API**: This API can be used in atomic services since API version 11.
624
625**System capability**: SystemCapability.ArkUI.ArkUI.Full
626
627## ImageErrorCallback<sup>9+</sup>
628
629type ImageErrorCallback = (error: ImageError) => void
630
631Represents the callback triggered when an error occurs during image loading.
632
633The callback is not triggered if the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
634
635**Widget capability**: This API can be used in ArkTS widgets since API version 9.
636
637**Atomic service API**: This API can be used in atomic services since API version 11.
638
639**System capability**: SystemCapability.ArkUI.ArkUI.Full
640
641| Name| Type                      | Mandatory| Description                              |
642| ------ | -------------------------- | ---- | ---------------------------------- |
643| error  | [ImageError](#imageerror9) | Yes  | Return object that triggers the callback for when an error occurs during image loading.|
644
645## ImageError<sup>9+</sup>
646
647Describes the return object that triggers the callback for when an error occurs during image loading.
648
649This event is not triggered if the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
650
651**Atomic service API**: This API can be used in atomic services since API version 11.
652
653**System capability**: SystemCapability.ArkUI.ArkUI.Full
654
655| Name         | Type  | Mandatory| Description                     |
656| --------------- | ------ | ---- | ------------------------- |
657| 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.|
658| 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.|
659| message<sup>10+</sup>         | string | Yes  | Error information.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 10.|
660
661## Example
662
663### Example 1: Loading Images of Basic Types
664
665This example demonstrates how to load images of basic types, such as PNG, GIF, SVG, and JPG.
666
667```ts
668@Entry
669@Component
670struct ImageExample1 {
671  build() {
672    Column() {
673      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
674        Row() {
675          // Load a PNG image.
676          Image($r('app.media.ic_camera_master_ai_leaf'))
677            .width(110).height(110).margin(15)
678            .overlay('png', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
679          // Load a GIF image.
680          Image($r('app.media.loading'))
681            .width(110).height(110).margin(15)
682            .overlay('gif', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
683        }
684        Row() {
685          // Load an SVG image.
686          Image($r('app.media.ic_camera_master_ai_clouded'))
687            .width(110).height(110).margin(15)
688            .overlay('svg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
689          // Load a JPG image.
690          Image($r('app.media.ic_public_favor_filled'))
691            .width(110).height(110).margin(15)
692            .overlay('jpg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
693        }
694      }
695    }.height(320).width(360).padding({ right: 10, top: 10 })
696  }
697}
698```
699
700![en-us_image_0000001592882500](figures/en-us_image_0000001592882500.gif)
701
702### Example 2: Downloading and Displaying Online Images
703
704The 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 in the **Image** component. For details about image development, see [Introduction to Image Kit](../../../media/image/image-overview.md).
705
706The **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).
707
708```ts
709import { http } from '@kit.NetworkKit';
710import { BusinessError } from '@kit.BasicServicesKit';
711import { image } from '@kit.ImageKit';
712
713@Entry
714@Component
715struct ImageExample2 {
716  @State pixelMapImg: PixelMap | undefined = undefined;
717
718  aboutToAppear() {
719    this.requestImageUrl('https://www.example.com/xxx.png');// Enter a specific online image URL.
720  }
721
722  requestImageUrl(url: string) {
723    http.createHttp().request(url, (error: BusinessError, data: http.HttpResponse)=> {
724      if (error) {
725        console.error(`request image failed: url: ${url}, code: ${error.code}, message: ${error.message}`);
726      } else {
727        let imgData: ArrayBuffer = data.result as ArrayBuffer;
728        console.info(`request image success, size: ${imgData.byteLength}`);
729        let imgSource: image.ImageSource = image.createImageSource(imgData);
730        class sizeTmp {
731          height: number = 100
732          width: number = 100
733        }
734        let options: Record<string, number | boolean | sizeTmp> = {
735          'alphaType': 0,
736          'editable': false,
737          'pixelFormat': 3,
738          'scaleMode': 1,
739          'size': { height: 100, width: 100 }
740        }
741        imgSource.createPixelMap(options).then((pixelMap: PixelMap) => {
742          console.error('image createPixelMap success');
743          this.pixelMapImg = pixelMap;
744        })
745      }
746    })
747  }
748
749  build() {
750    Column() {
751      Image(this.pixelMapImg)
752        .alt($r('app.media.img'))
753        .objectFit(ImageFit.None)
754        .width('100%')
755        .height('100%')
756    }
757  }
758}
759```
760
761![en-us_image_0000001607845173](figures/en-us_image_view2.gif)
762
763### Example 3: Adding Events to an Image
764
765This example shows how to add **onClick** and **onFinish** events to an image.
766
767```ts
768@Entry
769@Component
770struct ImageExample3 {
771  private imageOne: Resource = $r('app.media.earth');
772  private imageTwo: Resource = $r('app.media.star');
773  private imageThree: Resource = $r('app.media.moveStar');
774  @State src: Resource = this.imageOne
775  @State src2: Resource = this.imageThree
776  build(){
777    Column(){
778      // Add a click event so that a specific image is loaded upon clicking.
779      Image(this.src)
780        .width(100)
781        .height(100)
782        .onClick(() => {
783          this.src = this.imageTwo
784        })
785
786      // When the image to be loaded is in SVG format:
787      Image(this.src2)
788        .width(100)
789        .height(100)
790        .onFinish(() => {
791          // Load another image when the SVG image has finished its animation.
792          this.src2 = this.imageOne
793        })
794    }.width('100%').height('100%')
795  }
796}
797```
798
799![en-us_image_0000001607845173](figures/en-us_image_0000001607845173.gif)
800
801### Example 4: Enabling the AI Analyzer
802<!--RP2-->
803This example shows how to use **enableAnalyzer** to enable the AI analyzer.
804
805```ts
806import { image } from '@kit.ImageKit'
807
808@Entry
809@Component
810struct ImageExample4 {
811  @State imagePixelMap: image.PixelMap | undefined = undefined
812  private aiController: ImageAnalyzerController = new ImageAnalyzerController()
813  private options: ImageAIOptions = {
814    types: [ImageAnalyzerType.SUBJECT, ImageAnalyzerType.TEXT],
815    aiController: this.aiController
816  }
817
818  async aboutToAppear() {
819    this.imagePixelMap = await this.getPixmapFromMedia($r('app.media.app_icon'))
820  }
821
822  build() {
823    Column() {
824      Image(this.imagePixelMap, this.options)
825        .enableAnalyzer(true)
826        .width(200)
827        .height(200)
828        .margin({bottom:10})
829      Button('getTypes')
830        .width(80)
831        .height(80)
832        .onClick(() => {
833          this.aiController.getImageAnalyzerSupportTypes()
834        })
835    }
836  }
837  private async getPixmapFromMedia(resource: Resource) {
838    let unit8Array = await getContext(this)?.resourceManager?.getMediaContent({
839      bundleName: resource.bundleName,
840      moduleName: resource.moduleName,
841      id: resource.id
842    })
843    let imageSource = image.createImageSource(unit8Array.buffer.slice(0, unit8Array.buffer.byteLength))
844    let createPixelMap: image.PixelMap = await imageSource.createPixelMap({
845      desiredPixelFormat: image.PixelMapFormat.RGBA_8888
846    })
847    await imageSource.release()
848    return createPixelMap
849  }
850}
851```
852
853![en-us_image_0000001607845173](figures/en-us_image_view4.gif)
854<!--RP2End-->
855### Example 5: Resizing an Image
856
857This example shows how to resize an image in different directions.
858
859```ts
860@Entry
861@Component
862struct Index {
863  @State top: number = 40
864  @State bottom: number = 5
865  @State left: number = 40
866  @State right: number = 10
867
868  build() {
869    Column({ space: 5 }) {
870      // Original image effect
871      Image($r("app.media.sky"))
872        .width(200).height(200)
873        .border({ width: 2, color: Color.Pink })
874        .objectFit(ImageFit.Contain)
875
876      // Set the resizable attribute to resize the image in different directions.
877      Image($r("app.media.sky"))
878        .resizable({
879          slice: {
880            left: this.left,
881            right: this.right,
882            top: this.top,
883            bottom: this.bottom
884          }
885        })
886        .width(200)
887        .height(200)
888        .border({ width: 2, color: Color.Pink })
889        .objectFit(ImageFit.Contain)
890
891      Row() {
892        Button("add top to " + this.top).fontSize(10)
893          .onClick(() => {
894            this.top += 2
895          })
896        Button("add bottom to " + this.bottom).fontSize(10)
897          .onClick(() => {
898            this.bottom += 2
899          })
900      }
901
902      Row() {
903        Button("add left to " + this.left).fontSize(10)
904          .onClick(() => {
905            this.left += 2
906          })
907        Button("add right to " + this.right).fontSize(10)
908          .onClick(() => {
909            this.right += 2
910          })
911      }
912
913    }
914    .justifyContent(FlexAlign.Start).width('100%').height('100%')
915  }
916}
917```
918
919![imageResizable](figures/imageResizable.gif)
920
921### Example 6: Playing a PixelMap Array Animation
922
923This example demonstrates how to play an animation of a **PixelMap** array using [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12).
924
925```ts
926import {AnimationOptions, AnimatedDrawableDescriptor} from '@kit.ArkUI'
927import { image } from '@kit.ImageKit'
928
929@Entry
930@Component
931struct ImageExample {
932  pixelmaps: Array<PixelMap>  = [];
933  options: AnimationOptions = {duration:2000, iterations:1};
934  @State animated: AnimatedDrawableDescriptor | undefined = undefined;
935
936  async aboutToAppear() {
937    this.pixelmaps = await this.getPixelMaps();
938    this.animated = new AnimatedDrawableDescriptor(this.pixelmaps, this.options);
939  }
940
941  build() {
942    Column() {
943      Row() {
944        Image(this.animated)
945          .width('500px').height('500px')
946          .onFinish(() => {
947            console.info("finish")
948          })
949      }.height('50%')
950      Row() {
951        Button('once').width(100).padding(5).onClick(() => {
952          this.options = {duration:2000, iterations:1};
953          this.animated = new AnimatedDrawableDescriptor(this.pixelmaps, this.options);
954        }).margin(5)
955        Button('infinite').width(100).padding(5).onClick(() => {
956          this.options = {duration:2000, iterations:-1};
957          this.animated = new AnimatedDrawableDescriptor(this.pixelmaps, this.options);
958        }).margin(5)
959      }
960    }.width('50%')
961  }
962
963  private async getPixmapListFromMedia(resource: Resource) {
964    let unit8Array = await getContext(this)?.resourceManager?.getMediaContent({
965      bundleName: resource.bundleName,
966      moduleName: resource.moduleName,
967      id: resource.id
968    })
969    let imageSource = image.createImageSource(unit8Array.buffer.slice(0, unit8Array.buffer.byteLength))
970    let createPixelMap: Array<image.PixelMap> = await imageSource.createPixelMapList({
971      desiredPixelFormat: image.PixelMapFormat.RGBA_8888
972    })
973    await imageSource.release()
974    return createPixelMap
975  }
976
977  private async getPixmapFromMedia(resource: Resource) {
978    let unit8Array = await getContext(this)?.resourceManager?.getMediaContent({
979      bundleName: resource.bundleName,
980      moduleName: resource.moduleName,
981      id: resource.id
982    })
983    let imageSource = image.createImageSource(unit8Array.buffer.slice(0, unit8Array.buffer.byteLength))
984    let createPixelMap: image.PixelMap = await imageSource.createPixelMap({
985      desiredPixelFormat: image.PixelMapFormat.RGBA_8888
986    })
987    await imageSource.release()
988    return createPixelMap
989  }
990
991  private async getPixelMaps() {
992    let Mypixelmaps:Array<PixelMap> = await this.getPixmapListFromMedia($r('app.media.view'))// A GIF image, when processed, can generate multiple PixelMap instances.
993    Mypixelmaps.push(await this.getPixmapFromMedia($r('app.media.icon'))) // Add an image.
994    return Mypixelmaps;
995  }
996}
997```
998
999![en-us_image_0000001607845173](figures/en-us_image_view6.gif)
1000
1001### Example 7: Setting a Color Filter for an Image
1002
1003This example shows how to set a color filter for an image using [colorFilter](#colorfilter9).
1004
1005```ts
1006import { drawing, common2D } from '@kit.ArkGraphics2D';
1007
1008@Entry
1009@Component
1010struct ImageExample3 {
1011  private imageOne: Resource = $r('app.media.1');
1012  private imageTwo: Resource = $r('app.media.2');
1013  @State src: Resource = this.imageOne
1014  @State src2: Resource = this.imageTwo
1015  private ColorFilterMatrix: number[] = [1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0]
1016  private color: common2D.Color = { alpha: 255, red: 255, green: 0, blue: 0 };
1017  @State DrawingColorFilterFirst: ColorFilter | undefined = undefined
1018  @State DrawingColorFilterSecond: ColorFilter | undefined = undefined
1019  @State DrawingColorFilterThird: ColorFilter | undefined = undefined
1020
1021  build() {
1022    Column() {
1023      Image(this.src)
1024        .width(100)
1025        .height(100)
1026        .colorFilter(this.DrawingColorFilterFirst)
1027        .onClick(()=>{
1028          this.DrawingColorFilterFirst = drawing.ColorFilter.createBlendModeColorFilter(this.color, drawing.BlendMode.SRC_IN);
1029        })
1030
1031      Image(this.src2)
1032        .width(100)
1033        .height(100)
1034        .colorFilter(this.DrawingColorFilterSecond)
1035        .onClick(()=>{
1036          this.DrawingColorFilterSecond = new ColorFilter(this.ColorFilterMatrix);
1037        })
1038
1039      // When the image to be loaded is in SVG format:
1040      Image($r('app.media.test_self'))
1041        .width(110).height(110).margin(15)
1042        .colorFilter(this.DrawingColorFilterThird)
1043        .onClick(()=>{
1044          this.DrawingColorFilterThird = drawing.ColorFilter.createBlendModeColorFilter(this.color, drawing.BlendMode.SRC_IN);
1045        })
1046    }
1047  }
1048}
1049```
1050![imageSetColorFilter](figures/imageSetColorFilter.gif)
1051
1052### Example 8: Setting the Fill Effect for an Image
1053
1054This example shows how to [objectFit](#objectfit) to specify how an image is resized to fit its container.
1055
1056```ts
1057@Entry
1058@Component
1059struct ImageExample{
1060  build() {
1061    Column() {
1062      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
1063        Row() {
1064          // Load a PNG image.
1065          Image($r('app.media.sky'))
1066            .width(110).height(110).margin(15)
1067            .overlay('png', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
1068            .border({ width: 2, color: Color.Pink })
1069            .objectFit(ImageFit.TOP_START)
1070          // Load a GIF image.
1071          Image($r('app.media.loading'))
1072            .width(110).height(110).margin(15)
1073            .overlay('gif', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
1074            .border({ width: 2, color: Color.Pink })
1075            .objectFit(ImageFit.BOTTOM_START)
1076        }
1077        Row() {
1078          // Load an SVG image.
1079          Image($r('app.media.svg'))
1080            .width(110).height(110).margin(15)
1081            .overlay('svg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
1082            .border({ width: 2, color: Color.Pink })
1083            .objectFit(ImageFit.TOP_END)
1084          // Load a JPG image.
1085          Image($r('app.media.jpg'))
1086            .width(110).height(110).margin(15)
1087            .overlay('jpg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
1088            .border({ width: 2, color: Color.Pink })
1089            .objectFit(ImageFit.CENTER)
1090        }
1091      }
1092    }.height(320).width(360).padding({ right: 10, top: 10 })
1093  }
1094}
1095```
1096
1097![imageResizable](figures/imageSetFit.gif)
1098
1099### Example 9: Switching Between Different Types of Images
1100
1101This example demonstrates the display effects of images when using ResourceStr type and ImageContent type as data sources.
1102
1103```ts
1104@Entry
1105@Component
1106struct ImageContentExample {
1107  @State imageSrcIndex: number = 0;
1108  @State imageSrcList: (ResourceStr | ImageContent)[] = [$r('app.media.app_icon'), ImageContent.EMPTY]
1109
1110  build() {
1111    Column({ space: 10 }) {
1112      Image(this.imageSrcList[this.imageSrcIndex])
1113        .width(100)
1114        .height(100)
1115      Button('Change Image src')
1116        .padding(20)
1117        .onClick(() => {
1118          this.imageSrcIndex = (this.imageSrcIndex + 1) % this.imageSrcList.length
1119        })
1120    }.width('100%')
1121    .padding(20)
1122  }
1123}
1124```
1125
1126![imageContent](figures/en-us_image_view9.gif)
1127
1128### Example 10: Securing Sensitive Information
1129
1130This example shows how to secure sensitive information on widgets using [privacySensitive](#privacysensitive12). The display requires widget framework support.
1131
1132```ts
1133@Entry
1134@Component
1135struct ImageExample {
1136  build() {
1137    Column({ space: 10 }) {
1138      Image($r("app.media.startIcon"))
1139        .width(50)
1140        .height(50)
1141        .margin({top :30})
1142        .privacySensitive(true)
1143    }
1144    .alignItems(HorizontalAlign.Center)
1145    .width("100%")
1146  }
1147}
1148```
1149
1150![imageContent](figures/en-us_image_view10.gif)
1151
1152### Example 11: Setting the Scan Effect for an Image
1153
1154This 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).
1155
1156```ts
1157import { curves } from '@kit.ArkUI';
1158
1159@Entry
1160@Component
1161struct ImageExample11 {
1162  private curve = curves.cubicBezier(0.33, 0, 0.67, 1);
1163  @State moveImg: string[] = ['imageScanEffect'];
1164  @State moveImgVisible: Visibility = Visibility.Visible;
1165  @State durationTime: number = 1500;
1166  @State iterationsTimes: number = -1;
1167  @State private opacityValue: number = 0.5;
1168  @State imageWidth: number = 450;
1169  @State visible: Visibility = Visibility.Hidden;
1170  @State stackBackgroundColor: string = '#E1E4E9';
1171  @State linePositionX: number = 0 - this.imageWidth;
1172  @State linePositionY: number = 0;
1173  @State imgResource: Resource | undefined = undefined;
1174
1175  startupAnimate() {
1176    this.moveImg.pop();
1177    this.moveImg.push('imageScanEffect');
1178    setTimeout(() => {
1179      this.imgResource = $r('app.media.img');
1180    }, 3000);
1181    animateTo({
1182      duration: this.durationTime,
1183      curve: this.curve,
1184      tempo: 1,
1185      iterations: this.iterationsTimes,
1186      delay: 0
1187    }, () => {
1188      this.linePositionX = this.imageWidth;
1189    })
1190  }
1191
1192  build() {
1193    Column() {
1194      Row() {
1195        Stack() {
1196          Image(this.imgResource)
1197            .width(this.imageWidth)
1198            .height(200)
1199            .objectFit(ImageFit.Contain)
1200            .visibility(this.visible)
1201            .onComplete(() => {
1202              this.visible = Visibility.Visible;
1203              this.moveImg.pop();
1204            })
1205            .onError(() =>{
1206              setTimeout(() => {
1207                this.visible = Visibility.Visible;
1208                this.moveImg.pop();
1209              }, 2600)
1210            })
1211          ForEach(this.moveImg, (item: string) => {
1212            Row()
1213              .width(this.imageWidth)
1214              .height(200)
1215              .visibility(this.moveImgVisible)
1216              .position({ x: this.linePositionX, y: this.linePositionY })
1217              .linearGradient({
1218                direction: GradientDirection.Right,
1219                repeating: false,
1220                colors: [[0xE1E4E9, 0], [0xFFFFFF, 0.75], [0xE1E4E9, 1]]
1221              })
1222              .opacity(this.opacityValue)
1223          })
1224        }
1225        .backgroundColor(this.visible ? this.stackBackgroundColor : undefined)
1226        .margin({top: 20, left: 20, right: 20})
1227        .borderRadius(20)
1228        .clip(true)
1229        .onAppear(() => {
1230          this.startupAnimate();
1231        })
1232      }
1233    }
1234  }
1235}
1236```
1237
1238![imageContent](figures/imageScanEffect.gif)
1239