ts-basic-components-image.md 23.2 KB
Newer Older
Z
zengyawen 已提交
1
# Image
Z
zengyawen 已提交
2

E
ester.zhou 已提交
3
The **\<Image>** component is used to render and display local and online images.
Z
zengyawen 已提交
4

E
ester.zhou 已提交
5 6
> **NOTE**
>
Z
zengyawen 已提交
7
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
Z
zengyawen 已提交
8 9


Z
zengyawen 已提交
10 11
## Required Permissions

E
ester.zhou 已提交
12
To use online images, the application must have the **ohos.permission.INTERNET** permission. For details about how to apply for a permission, see [Declaring Permissions](../../security/accesstoken-guidelines.md).
Z
zengyawen 已提交
13 14 15


## Child Components
Z
zengyawen 已提交
16

E
ester.zhou 已提交
17
Not supported
Z
zengyawen 已提交
18

Z
zengyawen 已提交
19 20 21

## APIs

E
ester.zhou 已提交
22
Image(src: PixelMap | ResourceStr | DrawableDescriptor)
Z
zengyawen 已提交
23

E
ester.zhou 已提交
24
Obtains an image from the specified source for subsequent rendering and display.
Z
zengyawen 已提交
25

E
ester.zhou 已提交
26 27
Since API version 9, this API is supported in ArkTS widgets.

E
ester.zhou 已提交
28 29
**Parameters**

E
ester.zhou 已提交
30 31
| Name | Type                                    | Mandatory  | Description                                    |
| ---- | ---------------------------------------- | ---- | ---------------------------------------- |
E
ester.zhou 已提交
32
| src  |  [PixelMap](../apis/js-apis-image.md#pixelmap7) \| ResourceStr\| [DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor) | Yes   | Image source. Both local and online images are supported.<br>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. Therefore, you are advised to use **\$r** to reference image resources that need to be used globally.<br>- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.<br>\- Base64 strings are supported. The value format is data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where [base64 data] is a Base64 string.<br/>\- Strings with the **datashare://** prefix are supported, which are used to access the image path provided by a Data ability.<br/>\- Strings with the **file:///data/storage** prefix are supported, which are used to read image resources in the **files** folder in the installation directory of the current application. Ensure that the application has the read permission to the files in the specified path.<br/>\- [DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor) objects are supported.<br/>- For details, see [Displaying Images](../../ui/arkts-graphics-display.md).<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://**, **datashare://**, or **file:///data/storage** prefix.<br>- ArkTS widgets do not support the [PixelMap](../apis/js-apis-image.md#pixelmap7) type.|
Z
zengyawen 已提交
33 34 35

## Attributes

E
ester.zhou 已提交
36 37
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.

E
ester.zhou 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| Name                      | Type                                    | Description                                      |
| ------------------------ | ---------------------------------------- | ---------------------------------------- |
| alt                      | string \| [Resource](ts-types.md#resource)| Placeholder image displayed during loading. Local images are supported.<br>Since API version 9, this API is supported in ArkTS widgets.|
| objectFit                | [ImageFit](ts-appendix-enums.md#imagefit) | Image scale mode.<br>Default value: **ImageFit.Cover**<br>Since API version 9, this API is supported in ArkTS widgets.|
| objectRepeat             | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Whether the image is repeated.<br>Default value: **ImageRepeat.NoRepeat**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute is not applicable to SVG images.|
| interpolation            | [ImageInterpolation](#imageinterpolation) | Interpolation effect of the image. This attribute is intended to alleviate aliasing that occurs when a low-definition image is zoomed in.<br>Default value: **ImageInterpolation.None**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute is not applicable to SVG images.<br>This attribute is not applicable to **PixelMap** objects.|
| renderMode               | [ImageRenderMode](#imagerendermode)      | Rendering mode of the image.<br>Default value: **ImageRenderMode.Original**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute is not applicable to SVG images.|
| sourceSize               | {<br>width: number,<br>height: number<br>} | Size of the decoded image. The original image is decoded into a **pixelMap** of the specified size, in px.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute is not applicable to **PixelMap** objects or SVG images.|
| matchTextDirection       | boolean                                  | Whether to display the image in the system language direction. When this parameter is set to true, the image is horizontally flipped in the right-to-left (RTL) language context.<br>Default value: **false**<br>Since API version 9, this API is supported in ArkTS widgets.|
| fitOriginalSize          | boolean                                  | Whether to fit the component to the original size of the image source when the component size is not set.<br>Default value: **false**<br>Since API version 9, this API is supported in ArkTS widgets.|
| fillColor                | [ResourceColor](ts-types.md#resourcecolor) | Fill color. This attribute only applies to an SVG image. Once set, the fill color will replace that of the SVG image.<br>Since API version 9, this API is supported in ArkTS widgets.|
| autoResize               | boolean                                  | Whether to resize the image source used for drawing based on the size of the display area during image decoding. This resizing can help reduce the memory usage.<br>Default value: **true**<br>Since API version 9, this API is supported in ArkTS widgets.|
| syncLoad<sup>8+</sup>    | boolean                                  | Whether to load the image synchronously. By default, the image is loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder diagram is not displayed.<br>Default value: **false**<br>Since API version 9, this API is supported in ArkTS widgets.|
| copyOption<sup>9+</sup>  | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether the image can be copied. (SVG images cannot be copied.)<br>When **copyOption** is set to a value other than **CopyOptions.None**, the image can be copied in various manners, such as long pressing, right-clicking, or pressing Ctrl+C.<br>Default value: **CopyOptions.None**<br>This API is supported in ArkTS widgets.|
| colorFilter<sup>9+</sup> | [ColorFilter](ts-types.md#colorfilter9)  | Color filter of the image.<br>This API is supported in ArkTS widgets.      |
| draggable<sup>9+</sup>   | boolean                                  | Whether the image is draggable. This attribute cannot be used together with the [onDragStart](ts-universal-events-drag-drop.md) event.<br>Default value: **false**<br>This API is supported in ArkTS widgets.|
E
ester.zhou 已提交
54 55 56

>  **NOTE**
>
E
ester.zhou 已提交
57
>  To use shortcut keys to copy the image, the image must be in focus. To enable the image to gain focus, set both the **focusable** and **focusOnTouch** attributes to **true**.
E
ester.zhou 已提交
58
>
E
ester.zhou 已提交
59
>  For SVG images, only the following tags are included in the supported list: **svg**, **rect**, **circle**, **ellipse**, **path**, **line**, **polyline**, and **polygon**.
E
ester.zhou 已提交
60 61

### ImageInterpolation
Z
zengyawen 已提交
62

E
ester.zhou 已提交
63 64
Since API version 9, this API is supported in ArkTS widgets.

E
ester.zhou 已提交
65 66 67 68 69 70 71 72 73
| Name    | Description                       |
| ------ | ------------------------- |
| None   | Interpolation image data is not used.               |
| High   | The interpolation image data is used at the high level, which may affect the image rendering speed.|
| Medium | The interpolation image data is used at the medium level.             |
| Low    | The interpolation image data is used at the low level.             |

### ImageRenderMode

E
ester.zhou 已提交
74 75
Since API version 9, this API is supported in ArkTS widgets.

E
ester.zhou 已提交
76 77 78 79
| Name      | Description                   |
| -------- | --------------------- |
| Original | The image is rendered based on the original image, including the color.       |
| Template | The image is rendered as a template image, and its color is ignored.|
Z
zengyawen 已提交
80 81 82

## Events

E
ester.zhou 已提交
83
In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
Z
zengyawen 已提交
84

E
ester.zhou 已提交
85 86 87 88 89
| Name                                      | Description                                    |
| ---------------------------------------- | ---------------------------------------- |
| onComplete(callback: (event?: { width: number, height: number, componentWidth: number,<br> componentHeight: number, loadingStatus: number }) =&gt; void) | Triggered when an image is successfully loaded. The size of the loaded image is returned.<br>- **width**: width of the image, in pixels.<br>- **height**: height of the image, in pixels.<br>- **componentWidth**: width of the container component, in pixels.<br>- **componentHeight**: height of the container component, in pixels.<br>- **loadingStatus**: image loading status.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value **1** means that the image is successfully loaded, and **0** means the opposite.|
| onError(callback: (event?: { componentWidth: number, componentHeight: number , message<sup>9+</sup>: string }) =&gt; void) | Triggered when an exception occurs during image loading.<br>- **componentWidth**: width of the container component, in pixels.<br>- **componentHeight**: height of the container component, in pixels.<br>Since API version 9, this API is supported in ArkTS widgets.|
| onFinish(event: () =&gt; void) | Triggered when the animation playback in the loaded SVG image is complete. If the animation is an infinite loop, this callback is not triggered.<br>Since API version 9, this API is supported in ArkTS widgets.|
Z
zengyawen 已提交
90 91 92

## Example

E
ester.zhou 已提交
93
### Loading Images
Z
zengyawen 已提交
94

E
ester.zhou 已提交
95
Load and display different types of images and set the scale mode of the images.
E
ester.zhou 已提交
96

E
ester.zhou 已提交
97 98
The **overlay** attribute sets the mask text of an image. For details, see [Overlay](ts-universal-attributes-overlay.md).

E
ester.zhou 已提交
99
```ts
Z
zengyawen 已提交
100 101 102
@Entry
@Component
struct ImageExample1 {
Z
zengyawen 已提交
103
  private on: string = 'www.example.com' 
Z
zengyawen 已提交
104 105 106 107 108 109 110 111
  @State src: string = this.on

  build() {
    Column() {
      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
        Text('default').fontSize(16).fontColor(0xcccccc).height(30)
        Row({ space: 5 }) {
          Image($r('app.media.ic_png'))
E
ester.zhou 已提交
112
            .width(110).height(110).border({ width: 1 })
Z
zengyawen 已提交
113 114
            .overlay('png', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          Image($r('app.media.ic_gif'))
E
ester.zhou 已提交
115
            .width(110).height(110).border({ width: 1 })
Z
zengyawen 已提交
116 117
            .overlay('gif', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          Image($r('app.media.ic_svg'))
E
ester.zhou 已提交
118
            .width(110).height(110).border({ width: 1 })
Z
zengyawen 已提交
119 120 121 122
            .overlay('svg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        }
        Row({ space: 5 }) {
          Image($r('app.media.img_example'))
E
ester.zhou 已提交
123
            .width(110).height(110).border({ width: 1 })
Z
zengyawen 已提交
124 125
            .overlay('jpg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          Image(this.src)
E
ester.zhou 已提交
126
            .width(110).height(110).border({ width: 1 })
Z
zengyawen 已提交
127 128 129 130 131 132 133 134
            .overlay('network', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        }.margin({ top: 25, bottom: 10 })
      }

      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
        Text('objectFit').fontSize(16).fontColor(0xcccccc).height(30)
        Row({ space: 5 }) {
          Image($r('app.media.img_example'))
E
ester.zhou 已提交
135
            .border({ width: 1 })
Z
zengyawen 已提交
136 137 138
            .objectFit(ImageFit.None).width(110).height(110)
            .overlay('None', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          Image($r('app.media.img_example'))
E
ester.zhou 已提交
139
            .border({ width: 1 })
Z
zengyawen 已提交
140 141 142
            .objectFit(ImageFit.Fill).width(110).height(110)
            .overlay('Fill', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          Image($r('app.media.img_example'))
E
ester.zhou 已提交
143
            .border({ width: 1 })
Z
zengyawen 已提交
144 145 146 147 148
            .objectFit(ImageFit.Cover).width(110).height(110)
            .overlay('Cover', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        }
        Row({ space: 5 }) {
          Image($r('app.media.img_example_w250'))
E
ester.zhou 已提交
149
            .border({ width: 1 })
Z
zengyawen 已提交
150 151 152
            .objectFit(ImageFit.Contain).width(110).height(110)
            .overlay('Contain', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          Image($r('app.media.img_example_w250'))
E
ester.zhou 已提交
153
            .border({ width: 1 })
Z
zengyawen 已提交
154 155 156 157 158 159 160 161 162
            .objectFit(ImageFit.ScaleDown).width(110).height(110)
            .overlay('ScaleDown', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        }.margin({ top: 25 })
      }
    }.height(320).width(360).padding({ right: 10, top: 10 })
  }
}
```

Z
zengyawen 已提交
163 164
![en-us_image_0000001211898484](figures/en-us_image_0000001211898484.gif)

E
ester.zhou 已提交
165 166 167 168


### Loading Online Images

E
ester.zhou 已提交
169
The default network timeout period is 5 minutes for loading online images. When using an online image, you are advised to use **alt** to configure the placeholder image displayed during loading. If more flexible network configuration is required, you can use the [HTTP](../../connectivity/http-request.md) tool provided in the SDK to send a network request, and then decode the returned data into **PixelMap** objects in the **\<Image>** component. For details about image development, see [Image Processing](../../media/image-overview.md). The code snippet is as follows:
E
ester.zhou 已提交
170 171 172 173

```tsx
// @ts-nocheck
import http from '@ohos.net.http';
E
ester.zhou 已提交
174
import ResponseCode from '@ohos.net.http'
E
ester.zhou 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187 188
import image from '@ohos.multimedia.image'


@Entry 
@Component 
struct Index {
    
  // Create a PixelMap state variable to receive online images.
  @State image: PixelMap = undefined

  build() {
    Column({space: 10}) {
      Button ("Get Online Image")
        .onClick(() => {
E
ester.zhou 已提交
189
          this.httpRequest()
E
ester.zhou 已提交
190 191 192 193 194 195 196 197 198 199
        })
      Image(this.image).height(100).width(100)
    }
    .width('100%')
    .height('100%')
    .padding(10)
  }

  // Request an online image.
  private httpRequest() {
E
ester.zhou 已提交
200
    let httpRequest = http.createHttp()
E
ester.zhou 已提交
201 202 203 204 205 206 207 208 209 210
	
    httpRequest.request(
      "https://www.example.com/xxx.png",   // Enter a specific URL of the online image.
      (error, data) => {
        if(error) {
          console.log("error code: " + error.code + ", msg: " + error.message)
        } else {
          let code = data.responseCode
          if(ResponseCode.ResponseCode.OK == code) {
            let imageSource = image.createImageSource(data.result)
E
ester.zhou 已提交
211
            let options = {alphaType: 0,                     // Opacity
E
ester.zhou 已提交
212 213 214 215 216 217 218 219
                           editable: false,                  // Whether the image is editable
                           pixelFormat: 3,                   // Pixel format
                           scaleMode: 1,                     // Scale mode
                           size: {height: 100, width: 100}} // Image size
            imageSource.createPixelMap(options).then((pixelMap) => {
              this.image = pixelMap
            })
          } else {
E
ester.zhou 已提交
220
            console.log("response code: " + code)
E
ester.zhou 已提交
221 222 223 224 225 226 227 228
          }
        }
      }
    )
  }
}
```

E
ester.zhou 已提交
229
> **NOTE**
E
ester.zhou 已提交
230
>
E
ester.zhou 已提交
231
> For details about the request mode, timeout, and additional request parameters for loading online images, see [request()](../../reference/apis/js-apis-http.md) in the HTTP module.
E
ester.zhou 已提交
232

E
ester.zhou 已提交
233
### Setting Attributes
Z
zengyawen 已提交
234

E
ester.zhou 已提交
235
```ts
Z
zengyawen 已提交
236 237 238 239 240 241 242 243 244 245
@Entry
@Component
struct ImageExample2 {

  build() {
    Column({ space: 10 }) {
      Text('renderMode').fontSize(12).fontColor(0xcccccc).width('96%').height(30)
      Row({ space: 50 }) {
        Image($r('app.media.img_example'))
          .renderMode(ImageRenderMode.Original).width(100).height(100)
E
ester.zhou 已提交
246
          .border({ width: 1 })
Z
zengyawen 已提交
247 248 249
          .overlay('Original', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        Image($r('app.media.img_example'))
          .renderMode(ImageRenderMode.Template).width(100).height(100)
E
ester.zhou 已提交
250
          .border({ width: 1 })
Z
zengyawen 已提交
251 252
          .overlay('Template', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
      }
E
ester.zhou 已提交
253
      
Z
zengyawen 已提交
254 255 256
      Text('alt').fontSize(12).fontColor(0xcccccc).width('96%').height(30)
      Image('')
        .alt($r('app.media.Image_none'))
E
ester.zhou 已提交
257
        .width(100).height(100).border({ width: 1 })
E
ester.zhou 已提交
258
        
Z
zengyawen 已提交
259 260 261 262 263 264 265 266
      Text('sourceSize').fontSize(12).fontColor(0xcccccc).width('96%')
      Row({ space: 50 }) {
        Image($r('app.media.img_example'))
          .sourceSize({
            width: 150,
            height: 150
          })
          .objectFit(ImageFit.ScaleDown).width('25%').aspectRatio(1)
E
ester.zhou 已提交
267
          .border({ width: 1 })
Z
zengyawen 已提交
268 269 270 271 272 273 274
          .overlay('w:150 h:150', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        Image($r('app.media.img_example'))
          .sourceSize({
            width: 200,
            height: 200
          })
          .objectFit(ImageFit.ScaleDown).width('25%').aspectRatio(1)
E
ester.zhou 已提交
275
          .border({ width: 1 })
Z
zengyawen 已提交
276 277
          .overlay('w:200 h:200', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
      }
E
ester.zhou 已提交
278
      
Z
zengyawen 已提交
279 280 281
      Text('objectRepeat').fontSize(12).fontColor(0xcccccc).width('96%').height(30)
      Row({ space: 5 }) {
        Image($r('app.media.ic_health_heart'))
E
ester.zhou 已提交
282
          .width(120).height(125).border({ width: 1 })
Z
zengyawen 已提交
283 284 285
          .objectRepeat(ImageRepeat.XY).objectFit(ImageFit.ScaleDown)
          .overlay('ImageRepeat.XY', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        Image($r('app.media.ic_health_heart'))
E
ester.zhou 已提交
286
          .width(110).height(125).border({ width: 1 })
Z
zengyawen 已提交
287 288 289
          .objectRepeat(ImageRepeat.Y).objectFit(ImageFit.ScaleDown)
          .overlay('ImageRepeat.Y', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        Image($r('app.media.ic_health_heart'))
E
ester.zhou 已提交
290
          .width(110).height(125).border({ width: 1 })
Z
zengyawen 已提交
291 292 293 294 295 296 297 298
          .objectRepeat(ImageRepeat.X).objectFit(ImageFit.ScaleDown)
          .overlay('ImageRepeat.X', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
      }
    }.height(150).width('100%').padding({ right: 10 })
  }
}
```

Z
zengyawen 已提交
299 300
![en-us_image_0000001212058474](figures/en-us_image_0000001212058474.png)

E
ester.zhou 已提交
301
### Invoking Events
Z
zengyawen 已提交
302

E
ester.zhou 已提交
303
```ts
Z
zengyawen 已提交
304 305 306
@Entry
@Component
struct ImageExample3 {
E
ester.zhou 已提交
307 308
  @State widthValue: number = 0
  @State heightValue: number = 0
E
ester.zhou 已提交
309 310 311 312
  private on: Resource = $r('app.media.image_on')
  private off: Resource = $r('app.media.image_off')
  private on2off: Resource = $r('app.media.image_on2off')
  private off2on: Resource = $r('app.media.image_off2on')
Z
zengyawen 已提交
313 314 315 316 317 318 319 320 321 322 323 324 325 326
  @State src: Resource = this.on

  build() {
    Column() {
      Row({ space: 20 }) {
        Column() {
          Image($r('app.media.img_example1'))
            .alt($r('app.media.ic_public_picture'))
            .sourceSize({
              width: 900,
              height: 900
            })
            .objectFit(ImageFit.Cover)
            .height(180).width(180)
E
ester.zhou 已提交
327
            // Obtain the size of an image after the image loading is complete.
Z
zengyawen 已提交
328
            .onComplete((msg: { width: number,height: number }) => {
E
ester.zhou 已提交
329 330
              this.widthValue = msg.width
              this.heightValue = msg.height
Z
zengyawen 已提交
331 332 333 334
            })
            .onError(() => {
              console.log('load image fail')
            })
E
ester.zhou 已提交
335
            .overlay('\nwidth: ' + String(this.widthValue) + ' height: ' + String(this.heightValue), {
Z
zengyawen 已提交
336 337 338 339
              align: Alignment.Bottom,
              offset: { x: 0, y: 20 }
            })
        }
E
ester.zhou 已提交
340
        // Add a click event so that a specific image is loaded upon clicking.
Z
zengyawen 已提交
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
        Image(this.src)
          .width(120).height(120)
          .onClick(() => {
            if (this.src == this.on || this.src == this.off2on) {
              this.src = this.on2off
            } else {
              this.src = this.off2on
            }
          })
          .onFinish(() => {
            if (this.src == this.off2on) {
              this.src = this.on
            } else {
              this.src = this.off
            }
          })
      }
    }.width('100%')
  }
}
```

Z
zengyawen 已提交
363
![en-us_image_0000001256858397](figures/en-us_image_0000001256858397.gif)
E
ester.zhou 已提交
364 365 366 367

###  Rendering Sandbox Images

```ts
E
ester.zhou 已提交
368 369
import fileio from '@ohos.fileio';
import fs from '@ohos.file.fs';
E
ester.zhou 已提交
370
import context from '@ohos.app.ability.common';
E
ester.zhou 已提交
371 372 373 374 375 376

@Entry
@Component
struct LoadImageExample {
  @State resourcesPath: string = ''
  @State sandboxPath: string = ''
E
ester.zhou 已提交
377
  context: context.UIAbilityContext = getContext(this) as context.UIAbilityContext
E
ester.zhou 已提交
378 379 380 381 382 383 384 385

  build() {
    Column() {
      Button ('Read Sandbox Image')
        .margin({ bottom: 10, top: 10 })
        .onClick(() => {
          this.sandboxPath = this.context.getApplicationContext().filesDir + '/icon.png'
          console.log(`Read the sandbox image=========>${this.sandboxPath}`)
E
ester.zhou 已提交
386
          let fd = fs.openSync(this.sandboxPath, 0o100)
E
ester.zhou 已提交
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
          console.log(`create file========>${fd}`)
          let srcPath = this.context.bundleCodeDir + '/entry/resources/base/media/icon.png'
          console.log('mySrcpath' + srcPath)
          fileio.copyFileSync(srcPath, this.sandboxPath) // Copy the image to the sandbox path.
          this.sandboxPath = 'file://' + this.context.getApplicationContext().filesDir + '/icon.png'
        })
      Button ('Read Image')
        .margin({ bottom: 10 })
        .onClick(() => {
          this.resourcesPath = 'file://' + this.context.bundleCodeDir + '/entry/resources/base/media/icon.png'
        })
      Text(`Image path: ${this.resourcesPath}`)
        .fontSize(20)
        .margin({ bottom: 10 })
      Image(this.resourcesPath)
        .width(100)
        .height(100)
E
ester.zhou 已提交
404 405 406 407 408 409
        .colorFilter([
          0.30, 0.59, 0.11, 0, 0,
          0.30, 0.59, 0.11, 0, 0,
          0.30, 0.59, 0.11, 0, 0,
          0, 0, 0, 1.0, 0
        ])
E
ester.zhou 已提交
410 411 412 413 414 415 416 417 418 419 420
      Text(`Sandbox image path: ${this.sandboxPath}`)
        .fontSize(20)
        .margin({ bottom: 10 })
      Image(this.sandboxPath)
        .width(100)
        .height(100)
    }
    .width('100%').height('100%')
  }
}
```
E
ester.zhou 已提交
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503

### Applying a Filter to an Image

```ts
// xxx.ets
@Entry
@Component
struct colorFilterExample {
  @State colorFilterR: number = 0
  @State colorFilterG: number = 0
  @State colorFilterB: number = 0
  @State colorFilterA: number = 0

  build() {
    Row() {
      Column() {
        Image($r('app.media.sky'))
          .width(200)
          .height(200)
        Image($r('app.media.sky'))
          .width(200)
          .height(200)
          .colorFilter([
          this.colorFilterR, 0, this.colorFilterR, 0, 0,
            0, this.colorFilterG, this.colorFilterG, 0, 0,
          this.colorFilterB, 0, this.colorFilterB, 0, 0,
            0, 0, this.colorFilterA, 0, 0
          ])

        Row() {
          Text('R')
          Slider({
            min: 0,
            max: 1,
            step: 0.01
          })
            .onChange((valueR) => {
              this.colorFilterR = valueR
            })
        }

        Row() {
          Text('G')
          Slider({
            min: 0,
            max: 1,
            step: 0.01
          })
            .onChange((valueG) => {
              this.colorFilterG = valueG
            })
        }

        Row() {
          Text('B')
          Slider({
            min: 0,
            max: 1,
            step: 0.01
          })
            .onChange((valueB) => {
              this.colorFilterB = valueB
            })
        }

        Row() {
          Text('A')
          Slider({
            min: 0,
            max: 1,
            step: 0.01
          })
            .onChange((valueA) => {
              this.colorFilterA = valueA
            })
        }
      }.width('90%').alignItems(HorizontalAlign.Center)
    }.height('100%').width('100%').justifyContent(FlexAlign.Center)
  }
}
```

![colorFilter](figures/colorFilter.gif)