1# @ohos.multimedia.sendableImage (Image Processing Based on Sendable Objects) 2 3The **sendableImage** module provides APIs for image processing based on sendable objects. You can use the APIs to create a **PixelMap** object with specified properties or read pixels of an image (or even in a region of an image). 4 5> **NOTE** 6> 7> The initial APIs of this module are supported since API version 12. Newly added APIs will be marked with a superscript to indicate their earliest API version. 8 9## Modules to Import 10 11```ts 12import { sendableImage } from '@kit.ImageKit'; 13``` 14 15## sendableImage.createPixelMap 16 17createPixelMap(colors: ArrayBuffer, options: image.InitializationOptions): Promise\<PixelMap> 18 19Creates a **PixelMap** object with the default BGRA_8888 format and specified pixel properties. This API uses a promise to return the result. 20 21**System capability**: SystemCapability.Multimedia.Image.Core 22 23**Parameters** 24 25| Name | Type | Mandatory| Description | 26| ------- | ------------------------------------------------ | ---- | ---------------------------------------------------------------- | 27| colors | ArrayBuffer | Yes | Color array in BGRA_8888 format. | 28| options | [InitializationOptions](js-apis-image.md#initializationoptions8) | Yes | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable.| 29 30**Return value** 31 32| Type | Description | 33| -------------------------------- | ----------------------------------------------------------------------- | 34| Promise\<[PixelMap](#pixelmap)> | Promise used to return the **PixelMap** object.<br>If the size of the created PixelMap exceeds that of the original image, the PixelMap size of the original image is returned.| 35 36**Example** 37 38```ts 39import { image } from '@kit.ImageKit'; 40import { BusinessError } from '@kit.BasicServicesKit'; 41 42async function Demo() { 43 const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4. 44 let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } 45 sendableImage.createPixelMap(color, opts).then((pixelMap: sendableImage.PixelMap) => { 46 console.info('Succeeded in creating pixelmap.'); 47 }).catch((error: BusinessError) => { 48 console.error(`Failed to create pixelmap. code is ${error.code}, message is ${error.message}`); 49 }) 50} 51``` 52 53## sendableImage.createPixelMapFromParcel 54 55createPixelMapFromParcel(sequence: rpc.MessageSequence): PixelMap 56 57Creates a **PixelMap** object from a **MessageSequence** object. 58 59**System capability**: SystemCapability.Multimedia.Image.Core 60 61**Parameters** 62 63| Name | Type | Mandatory| Description | 64| ---------------------- | ----------------------------------------------------- | ---- | ---------------------------------------- | 65| sequence | [rpc.MessageSequence](../apis-ipc-kit/js-apis-rpc.md#messagesequence9) | Yes | **MessageSequence** object that stores the **PixelMap** information. | 66 67**Return value** 68 69| Type | Description | 70| -------------------------------- | --------------------- | 71| [PixelMap](#pixelmap) | Returns a **PixelMap** object if the operation is successful; throws an error otherwise.| 72 73**Error codes** 74 75For details about the error codes, see [Image Error Codes](errorcode-image.md). 76 77| ID| Error Message| 78| ------- | --------------------------------------------| 79| 62980096 | If the operation failed| 80| 62980097 | If the ipc error| 81| 62980115 | Invalid input parameter| 82| 62980105 | Failed to get the data| 83| 62980177 | Abnormal API environment| 84| 62980178 | Failed to create the PixelMap| 85| 62980179 | Abnormal buffer size| 86| 62980180 | FD mapping failed| 87| 62980246 | Failed to read the PixelMap| 88 89**Example** 90 91```ts 92import { sendableImage } from '@kit.ImageKit'; 93import { image } from '@kit.ImageKit'; 94import { rpc } from '@kit.IPCKit'; 95import { BusinessError } from '@kit.BasicServicesKit'; 96 97class MySequence implements rpc.Parcelable { 98 pixel_map: sendableImage.PixelMap; 99 constructor(conPixelmap: sendableImage.PixelMap) { 100 this.pixel_map = conPixelmap; 101 } 102 marshalling(messageSequence: rpc.MessageSequence) { 103 this.pixel_map.marshalling(messageSequence); 104 return true; 105 } 106 unmarshalling(messageSequence: rpc.MessageSequence) { 107 try { 108 this.pixel_map = sendableImage.createPixelMapFromParcel(messageSequence); 109 } catch(e) { 110 let error = e as BusinessError; 111 console.error(`createPixelMapFromParcel error. code is ${error.code}, message is ${error.message}`); 112 return false; 113 } 114 return true; 115 } 116} 117async function Demo() { 118 const color: ArrayBuffer = new ArrayBuffer(96); 119 let bufferArr: Uint8Array = new Uint8Array(color); 120 for (let i = 0; i < bufferArr.length; i++) { 121 bufferArr[i] = 0x80; 122 } 123 let opts: image.InitializationOptions = { 124 editable: true, 125 pixelFormat: 4, 126 size: { height: 4, width: 6 }, 127 alphaType: 3 128 } 129 let pixelMap: sendableImage.PixelMap | undefined = undefined; 130 sendableImage.createPixelMap(color, opts).then((srcPixelMap: sendableImage.PixelMap) => { 131 pixelMap = srcPixelMap; 132 }) 133 if (pixelMap != undefined) { 134 // Implement serialization. 135 let parcelable: MySequence = new MySequence(pixelMap); 136 let data: rpc.MessageSequence = rpc.MessageSequence.create(); 137 data.writeParcelable(parcelable); 138 139 // Implement deserialization to obtain data through the RPC. 140 let ret: MySequence = new MySequence(pixelMap); 141 data.readParcelable(ret); 142 143 // Obtain the PixelMap object. 144 let unmarshPixelmap = ret.pixel_map; 145 } 146} 147``` 148 149## sendableImage.createPixelMapFromSurface 150 151createPixelMapFromSurface(surfaceId: string, region: image.Region): Promise\<PixelMap> 152 153Creates a **PixelMap** object from a surface ID. 154 155**System capability**: SystemCapability.Multimedia.Image.Core 156 157**Parameters** 158 159| Name | Type | Mandatory| Description | 160| ---------------------- | ------------- | ---- | ---------------------------------------- | 161| surfaceId | string | Yes | Surface ID, which is obtained from [XComponent](../apis-arkui/arkui-ts/ts-basic-components-xcomponent.md).| 162| region | [Region](../apis-image-kit/js-apis-image.md#region8) | Yes | Size of the image after cropping. | 163 164**Return value** 165| Type | Description | 166| -------------------------------- | --------------------- | 167| Promise\<[PixelMap](#pixelmap)> | Returns a **PixelMap** object if the operation is successful; throws an error otherwise.| 168 169**Error codes** 170 171For details about the error codes, see [Image Error Codes](errorcode-image.md). 172 173| ID| Error Message| 174| ------- | --------------------------------------------| 175| 62980115 | Invalid input parameter| 176| 62980105 | Failed to get the data| 177| 62980178 | Failed to create the PixelMap| 178 179**Example** 180 181```ts 182import { image } from '@kit.ImageKit'; 183import { BusinessError } from '@kit.BasicServicesKit'; 184 185async function Demo(surfaceId: string) { 186 let region: image.Region = { x: 0, y: 0, size: { height: 100, width: 100 } }; 187 sendableImage.createPixelMapFromSurface(surfaceId, region).then(() => { 188 console.info('Succeeded in creating pixelmap from Surface'); 189 }).catch((error: BusinessError) => { 190 console.error(`Failed to create pixelmap. code is ${error.code}, message is ${error.message}`); 191 }); 192} 193``` 194 195## sendableImage.createPixelMapSync 196 197createPixelMapSync(colors: ArrayBuffer, options: image.InitializationOptions): PixelMap 198 199Creates a **PixelMap** object with the specified pixel properties. This API returns the result synchronously. 200 201**System capability**: SystemCapability.Multimedia.Image.Core 202 203**Parameters** 204 205| Name | Type | Mandatory| Description | 206| ------- | ------------------------------------------------ | ---- | ---------------------------------------------------------------- | 207| colors | ArrayBuffer | Yes | Color array in BGRA_8888 format. | 208| options | [InitializationOptions](js-apis-image.md#initializationoptions8) | Yes | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable.| 209 210**Return value** 211| Type | Description | 212| -------------------------------- | --------------------- | 213| [PixelMap](#pixelmap) | Returns a **PixelMap** object if the operation is successful; throws an error otherwise.| 214 215**Error codes** 216 217For details about the error codes, see [Image Error Codes](errorcode-image.md). 218 219| ID| Error Message| 220| ------- | --------------------------------------------| 221| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.| 222 223**Example** 224 225```ts 226import { image } from '@kit.ImageKit'; 227import { BusinessError } from '@kit.BasicServicesKit'; 228 229async function Demo() { 230 const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4. 231 let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } 232 let pixelMap : sendableImage.PixelMap = sendableImage.createPixelMapSync(color, opts); 233 return pixelMap; 234} 235``` 236 237## sendableImage.convertFromPixelMap 238 239convertFromPixelMap(pixelMap: image.PixelMap): PixelMap 240 241Creates a **PixelMap** object under **sendableImage** from a **PixelMap** object under **image**. This API returns the result synchronously. The APIs of the **PixelMap** object under **image** cannot be called anymore. 242 243**System capability**: SystemCapability.Multimedia.Image.Core 244 245**Parameters** 246 247| Name | Type | Mandatory| Description | 248| ------- | ------------------------------------------------ | ---- | ---------------------------------------------------------------- | 249| pixelMap | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | **PixelMap** object under **image**.| 250 251**Return value** 252| Type | Description | 253| -------------------------------- | --------------------- | 254| [PixelMap](#pixelmap) | Returns a **PixelMap** object, which is sendable, if the operation is successful; throws an error otherwise.| 255 256**Error codes** 257 258For details about the error codes, see [Image Error Codes](errorcode-image.md). 259 260| ID| Error Message| 261| ------- | --------------------------------------------| 262| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.| 263| 62980104 | Failed to initialize the internal object.| 264 265**Example** 266 267```ts 268import { image } from '@kit.ImageKit'; 269import { BusinessError } from '@kit.BasicServicesKit'; 270 271async function Demo() { 272 const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4. 273 let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } 274 let pixelMap : image.PixelMap = image.createPixelMapSync(color, opts); 275 let sendablePixelMap : sendableImage.PixelMap = sendableImage.convertFromPixelMap(pixelMap); 276 return sendablePixelMap; 277} 278``` 279 280## sendableImage.convertToPixelMap 281 282convertToPixelMap(pixelMap: PixelMap): image.PixelMap 283 284Creates a **PixelMap** object under **image** from a **PixelMap** object under **sendableImage**. This API returns the result synchronously. The APIs of the **PixelMap** object under **sendableImage** cannot be called anymore. 285 286**System capability**: SystemCapability.Multimedia.Image.Core 287 288**Parameters** 289 290| Name | Type | Mandatory| Description | 291| ------- | ------------------------------------------------ | ---- | ---------------------------------------------------------------- | 292| pixelMap | [PixelMap](#pixelmap) | Yes | PixelMap object under **sendableImage**.| 293 294**Return value** 295| Type | Description | 296| -------------------------------- | --------------------- | 297| [PixelMap](js-apis-image.md#pixelmap7) | Returns a **PixelMap** object, which is not sendable, if the operation is successful; throws an error otherwise.| 298 299**Error codes** 300 301For details about the error codes, see [Image Error Codes](errorcode-image.md). 302 303| ID| Error Message| 304| ------- | --------------------------------------------| 305| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.| 306| 62980104 | Failed to initialize the internal object.| 307 308**Example** 309 310```ts 311import { image } from '@kit.ImageKit'; 312import { BusinessError } from '@kit.BasicServicesKit'; 313 314async function Demo() { 315 const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4. 316 let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } 317 let sendablePixelMap : sendableImage.PixelMap = sendableImage.createPixelMapSync(color, opts); 318 let pixelMap : image.PixelMap = sendableImage.convertToPixelMap(sendablePixelMap); 319 return pixelMap; 320} 321``` 322 323## PixelMap 324 325Provides APIs to read or write image data and obtain image information. Before calling any API in **PixelMap**, you must use [createPixelMap](#sendableimagecreatepixelmap) to create a **PixelMap** object. Currently, the maximum size of a serialized PixelMap is 128 MB. A larger size will cause a display failure. The size is calculated as follows: Width * Height * Number of bytes occupied by each pixel. 326 327The **PixelMap** object under **sendableImage** supports the **sendable** attribute and sharing of the worker thread. The [Convert](#sendableimageconverttopixelmap) API can be used to convert a **PixelMap** object in **sendableImage** to a **PixelMap** object in **image**, and vise versa. After the conversion, the APIs of the original object cannot be called. Otherwise, error 501 is reported. When processing a **PixelMap** object across threads, you need to consider the multithreaded problem. 328 329Before calling any API in **PixelMap**, you must use [sendableImage.createPixelMap](#sendableimagecreatepixelmap) to create a **PixelMap** object. 330 331### Attributes 332 333**System capability**: SystemCapability.Multimedia.Image.Core 334 335| Name | Type | Readable| Writable| Description | 336| -----------------| ------- | ---- | ---- | -------------------------- | 337| isEditable | boolean | Yes | No | Whether the pixels of an image are editable.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 338| isStrideAlignment | boolean | Yes | No | Whether the image memory is the DMA memory. In the case of DMA, a 256-byte alignment is carried out, which means that a padding area exists at the end of the line.| 339 340### readPixelsToBuffer 341 342readPixelsToBuffer(dst: ArrayBuffer): Promise\<void> 343 344Reads the pixels of this image and writes the data to an ArrayBuffer. This API uses a promise to return the result. If the PixelMap is created in the BGRA_8888 format, the data read is the same as the original data. 345 346**Atomic service API**: This API can be used in atomic services since API version 12. 347 348**System capability**: SystemCapability.Multimedia.Image.Core 349 350**Parameters** 351 352| Name| Type | Mandatory| Description | 353| ------ | ----------- | ---- | ----------------------------------------------------------------------------------------------------- | 354| dst | ArrayBuffer | Yes | Buffer to which the pixels will be written. The buffer size is obtained by calling [getPixelBytesNumber](#getpixelbytesnumber).| 355 356**Return value** 357 358| Type | Description | 359| -------------- | ----------------------------------------------- | 360| Promise\<void> | Promise used to return the result. If the operation fails, an error message is returned.| 361 362**Example** 363 364```ts 365import { BusinessError } from '@kit.BasicServicesKit'; 366 367async function Demo() { 368 const readBuffer: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4. 369 if (pixelMap != undefined) { 370 pixelMap.readPixelsToBuffer(readBuffer).then(() => { 371 console.info('Succeeded in reading image pixel data.'); // Called if the condition is met. 372 }).catch((error: BusinessError) => { 373 console.error(`Failed to read image pixel data. code is ${error.code}, message is ${error.message}`); // Called if no condition is met. 374 }) 375 } 376} 377``` 378 379### readPixelsToBufferSync 380 381readPixelsToBufferSync(dst: ArrayBuffer): void 382 383Reads the pixels of this image and writes the data to an ArrayBuffer. This API returns the result synchronously. 384 385**Atomic service API**: This API can be used in atomic services since API version 12. 386 387**System capability**: SystemCapability.Multimedia.Image.Core 388 389**Parameters** 390 391| Name | Type | Mandatory| Description | 392| -------- | -------------------- | ---- | ----------------------------------------------------------------------------------------------------- | 393| dst | ArrayBuffer | Yes | Buffer to which the pixels will be written. The buffer size is obtained by calling [getPixelBytesNumber](#getpixelbytesnumber).| 394 395**Error codes** 396 397For details about the error codes, see [Image Error Codes](errorcode-image.md). 398 399| ID| Error Message| 400| ------- | --------------------------------------------| 401| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. | 402| 501 | Resource Unavailable. | 403 404**Example** 405 406```ts 407import { BusinessError } from '@kit.BasicServicesKit'; 408 409async function Demo() { 410 const readBuffer: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4. 411 if (pixelMap != undefined) { 412 pixelMap.readPixelsToBufferSync(readBuffer); 413 } 414} 415``` 416 417### readPixels 418 419readPixels(area: image.PositionArea): Promise\<void> 420 421Reads the pixels in an area. This API uses a promise to return the result. 422 423**Atomic service API**: This API can be used in atomic services since API version 12. 424 425**System capability**: SystemCapability.Multimedia.Image.Core 426 427**Parameters** 428 429| Name| Type | Mandatory| Description | 430| ------ | ------------------------------ | ---- | ------------------------ | 431| area | [PositionArea](js-apis-image.md#positionarea7) | Yes | Area from which the pixels will be read.| 432 433**Return value** 434 435| Type | Description | 436| :------------- | :-------------------------------------------------- | 437| Promise\<void> | Promise used to return the result. If the operation fails, an error message is returned.| 438 439**Example** 440 441```ts 442import { image } from '@kit.ImageKit'; 443import { BusinessError } from '@kit.BasicServicesKit'; 444 445async function Demo() { 446 const area: image.PositionArea = { 447 pixels: new ArrayBuffer(8), 448 offset: 0, 449 stride: 8, 450 region: { size: { height: 1, width: 2 }, x: 0, y: 0 } 451 }; 452 if (pixelMap != undefined) { 453 pixelMap.readPixels(area).then(() => { 454 console.info('Succeeded in reading the image data in the area.'); // Called if the condition is met. 455 }).catch((error: BusinessError) => { 456 console.error(`Failed to read the image data in the area. code is ${error.code}, message is ${error.message}`); // Called if no condition is met. 457 }) 458 } 459} 460``` 461 462### readPixelsSync 463 464readPixelsSync(area: image.PositionArea): void 465 466Reads the pixels in an area. This API returns the result synchronously. 467 468**Atomic service API**: This API can be used in atomic services since API version 12. 469 470**System capability**: SystemCapability.Multimedia.Image.Core 471 472**Parameters** 473 474| Name| Type | Mandatory| Description | 475| ------ | ------------------------------ | ---- | ------------------------ | 476| area | [PositionArea](js-apis-image.md#positionarea7) | Yes | Area from which the pixels will be read.| 477 478**Error codes** 479 480For details about the error codes, see [Image Error Codes](errorcode-image.md). 481 482| ID| Error Message| 483| ------- | --------------------------------------------| 484| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. | 485| 501 | Resource Unavailable. | 486 487**Example** 488 489```ts 490import { image } from '@kit.ImageKit'; 491import { BusinessError } from '@kit.BasicServicesKit'; 492 493async function Demo() { 494 const area : image.PositionArea = { 495 pixels: new ArrayBuffer(8), 496 offset: 0, 497 stride: 8, 498 region: { size: { height: 1, width: 2 }, x: 0, y: 0 } 499 }; 500 if (pixelMap != undefined) { 501 pixelMap.readPixelsSync(area); 502 } 503} 504``` 505 506### writePixels 507 508writePixels(area: image.PositionArea): Promise\<void> 509 510Writes the pixels to an area. This API uses a promise to return the result. 511 512**Atomic service API**: This API can be used in atomic services since API version 12. 513 514**System capability**: SystemCapability.Multimedia.Image.Core 515 516**Parameters** 517 518| Name| Type | Mandatory| Description | 519| ------ | ------------------------------ | ---- | -------------------- | 520| area | [PositionArea](js-apis-image.md#positionarea7) | Yes | Area to which the pixels will be written.| 521 522**Return value** 523 524| Type | Description | 525| :------------- | :-------------------------------------------------- | 526| Promise\<void> | Promise used to return the result. If the operation fails, an error message is returned.| 527 528**Example** 529 530```ts 531import { image } from '@kit.ImageKit'; 532import { BusinessError } from '@kit.BasicServicesKit'; 533 534async function Demo() { 535 const area: image.PositionArea = { 536 pixels: new ArrayBuffer(8), 537 offset: 0, 538 stride: 8, 539 region: { size: { height: 1, width: 2 }, x: 0, y: 0 } 540 }; 541 let bufferArr: Uint8Array = new Uint8Array(area.pixels); 542 for (let i = 0; i < bufferArr.length; i++) { 543 bufferArr[i] = i + 1; 544 } 545 if (pixelMap != undefined) { 546 pixelMap.writePixels(area).then(() => { 547 console.info('Succeeded to write pixelmap into the specified area.'); 548 }).catch((error: BusinessError) => { 549 console.error(`Failed to write pixelmap into the specified area. code is ${error.code}, message is ${error.message}`); 550 }) 551 } 552} 553``` 554 555### writePixelsSync 556 557writePixelsSync(area: image.PositionArea): void 558 559Writes the pixels to an area. This API returns the result synchronously. 560 561**Atomic service API**: This API can be used in atomic services since API version 12. 562 563**System capability**: SystemCapability.Multimedia.Image.Core 564 565**Parameters** 566 567| Name| Type | Mandatory| Description | 568| ------ | ------------------------------ | ---- | -------------------- | 569| area | [PositionArea](js-apis-image.md#positionarea7) | Yes | Area to which the pixels will be written.| 570 571**Error codes** 572 573For details about the error codes, see [Image Error Codes](errorcode-image.md). 574 575| ID| Error Message| 576| ------- | --------------------------------------------| 577| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. | 578| 501 | Resource Unavailable. | 579 580**Example** 581 582```ts 583import { image } from '@kit.ImageKit'; 584import { BusinessError } from '@kit.BasicServicesKit'; 585 586async function Demo() { 587 const area: image.PositionArea = { 588 pixels: new ArrayBuffer(8), 589 offset: 0, 590 stride: 8, 591 region: { size: { height: 1, width: 2 }, x: 0, y: 0 } 592 }; 593 let bufferArr: Uint8Array = new Uint8Array(area.pixels); 594 for (let i = 0; i < bufferArr.length; i++) { 595 bufferArr[i] = i + 1; 596 } 597 if (pixelMap != undefined) { 598 pixelMap.writePixelsSync(area); 599 } 600} 601``` 602 603### writeBufferToPixels 604 605writeBufferToPixels(src: ArrayBuffer): Promise\<void> 606 607Reads image data in an ArrayBuffer and writes the data to a **PixelMap** object. This API uses a promise to return the result. 608 609**Atomic service API**: This API can be used in atomic services since API version 12. 610 611**System capability**: SystemCapability.Multimedia.Image.Core 612 613**Parameters** 614 615| Name| Type | Mandatory| Description | 616| ------ | ----------- | ---- | -------------- | 617| src | ArrayBuffer | Yes | Buffer from which the image data will be read.| 618 619**Return value** 620 621| Type | Description | 622| -------------- | ----------------------------------------------- | 623| Promise\<void> | Promise used to return the result. If the operation fails, an error message is returned.| 624 625**Example** 626 627```ts 628import { BusinessError } from '@kit.BasicServicesKit'; 629 630async function Demo() { 631 const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4. 632 let bufferArr: Uint8Array = new Uint8Array(color); 633 for (let i = 0; i < bufferArr.length; i++) { 634 bufferArr[i] = i + 1; 635 } 636 if (pixelMap != undefined) { 637 pixelMap.writeBufferToPixels(color).then(() => { 638 console.info("Succeeded in writing data from a buffer to a PixelMap."); 639 }).catch((error: BusinessError) => { 640 console.error(`Failed to write data from a buffer to a PixelMap. code is ${error.code}, message is ${error.message}`); 641 }) 642 } 643} 644``` 645 646### writeBufferToPixelsSync 647 648writeBufferToPixelsSync(src: ArrayBuffer): void 649 650Reads image data in an ArrayBuffer and writes the data to a **PixelMap** object. This API returns the result synchronously. 651 652**Atomic service API**: This API can be used in atomic services since API version 12. 653 654**System capability**: SystemCapability.Multimedia.Image.Core 655 656**Parameters** 657 658| Name| Type | Mandatory| Description | 659| ------ | ----------- | ---- | -------------- | 660| src | ArrayBuffer | Yes | Buffer from which the image data will be read.| 661 662**Error codes** 663 664For details about the error codes, see [Image Error Codes](errorcode-image.md). 665 666| ID| Error Message| 667| ------- | --------------------------------------------| 668| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. | 669| 501 | Resource Unavailable. | 670 671**Example** 672 673```ts 674import { BusinessError } from '@kit.BasicServicesKit'; 675 676async function Demo() { 677 const color : ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4. 678 let bufferArr : Uint8Array = new Uint8Array(color); 679 for (let i = 0; i < bufferArr.length; i++) { 680 bufferArr[i] = i + 1; 681 } 682 if (pixelMap != undefined) { 683 pixelMap.writeBufferToPixelsSync(color); 684 } 685} 686``` 687 688### getImageInfo 689 690getImageInfo(): Promise\<image.ImageInfo> 691 692Obtains the image information. This API uses a promise to return the result. 693 694**Atomic service API**: This API can be used in atomic services since API version 12. 695 696**System capability**: SystemCapability.Multimedia.Image.Core 697 698**Return value** 699 700| Type | Description | 701| --------------------------------- | ----------------------------------------------------------- | 702| Promise\<[ImageInfo](js-apis-image.md#imageinfo)> | Promise used to return the image information. If the operation fails, an error message is returned.| 703 704**Example** 705 706```ts 707import { image } from '@kit.ImageKit'; 708import { BusinessError } from '@kit.BasicServicesKit'; 709 710async function Demo() { 711 if (pixelMap != undefined) { 712 pixelMap.getImageInfo().then((imageInfo: image.ImageInfo) => { 713 if (imageInfo != undefined) { 714 console.info("Succeeded in obtaining the image pixel map information."+ imageInfo.size.height); 715 } 716 }).catch((error: BusinessError) => { 717 console.error(`Failed to obtain the image pixel map information. code is ${error.code}, message is ${error.message}`); 718 }) 719 } 720} 721``` 722 723### getImageInfoSync 724 725getImageInfoSync(): image.ImageInfo 726 727Obtains the image information. This API returns the result synchronously. 728 729**Atomic service API**: This API can be used in atomic services since API version 12. 730 731**System capability**: SystemCapability.Multimedia.Image.ImageSource 732 733**Return value** 734 735| Type | Description | 736| --------------------------------- | ----------------------------------------------------------- | 737| [ImageInfo](js-apis-image.md#imageinfo) | Image information. | 738 739**Error codes** 740 741For details about the error codes, see [Image Error Codes](errorcode-image.md). 742 743| ID| Error Message| 744| ------- | --------------------------------------------| 745| 501 | Resource Unavailable | 746 747**Example** 748 749```ts 750import { image } from '@kit.ImageKit'; 751import { BusinessError } from '@kit.BasicServicesKit'; 752 753async function Demo() { 754 if (pixelMap != undefined) { 755 let imageInfo : image.ImageInfo = pixelMap.getImageInfoSync(); 756 } 757} 758``` 759 760### getBytesNumberPerRow 761 762getBytesNumberPerRow(): number 763 764Obtains the number of bytes per row of this image. 765 766**Atomic service API**: This API can be used in atomic services since API version 12. 767 768**System capability**: SystemCapability.Multimedia.Image.Core 769 770**Return value** 771 772| Type | Description | 773| ------ | -------------------- | 774| number | Number of bytes per row.| 775 776**Example** 777 778```ts 779let rowCount: number = pixelMap.getBytesNumberPerRow(); 780``` 781 782### getPixelBytesNumber 783 784getPixelBytesNumber(): number 785 786Obtains the total number of bytes of this image. 787 788**Atomic service API**: This API can be used in atomic services since API version 12. 789 790**System capability**: SystemCapability.Multimedia.Image.Core 791 792**Return value** 793 794| Type | Description | 795| ------ | -------------------- | 796| number | Total number of bytes.| 797 798**Example** 799 800```ts 801let pixelBytesNumber: number = pixelMap.getPixelBytesNumber(); 802``` 803 804### getDensity 805 806getDensity():number 807 808Obtains the density of this image. 809 810**Atomic service API**: This API can be used in atomic services since API version 12. 811 812**System capability**: SystemCapability.Multimedia.Image.Core 813 814**Return value** 815 816| Type | Description | 817| ------ | --------------- | 818| number | Density of the image.| 819 820**Example** 821 822```ts 823let getDensity: number = pixelMap.getDensity(); 824``` 825 826### opacity 827 828opacity(rate: number): Promise\<void> 829 830Sets an opacity rate for this image. This API uses a promise to return the result. 831 832**Atomic service API**: This API can be used in atomic services since API version 12. 833 834**System capability**: SystemCapability.Multimedia.Image.Core 835 836**Parameters** 837 838| Name| Type | Mandatory| Description | 839| ------ | ------ | ---- | --------------------------- | 840| rate | number | Yes | Opacity rate.| 841 842**Return value** 843 844| Type | Description | 845| -------------- | ----------------------------------------------- | 846| Promise\<void> | Promise used to return the result. If the operation fails, an error message is returned.| 847 848**Example** 849 850```ts 851import { BusinessError } from '@kit.BasicServicesKit'; 852 853async function Demo() { 854 let rate: number = 0.5; 855 if (pixelMap != undefined) { 856 pixelMap.opacity(rate).then(() => { 857 console.info('Succeeded in setting opacity.'); 858 }).catch((err: BusinessError) => { 859 console.error(`Failed to set opacity. code is ${err.code}, message is ${err.message}`); 860 }) 861 } 862} 863``` 864 865### opacitySync 866 867opacitySync(rate: number): void 868 869Sets the opacity rate for this PixelMap and initializes the PixelMap. 870 871**Atomic service API**: This API can be used in atomic services since API version 12. 872 873**System capability**: SystemCapability.Multimedia.Image.Core 874 875**Parameters** 876 877| Name | Type | Mandatory| Description | 878| -------- | -------------------- | ---- | ------------------------------ | 879| rate | number | Yes | Opacity rate. | 880 881**Error codes** 882 883For details about the error codes, see [Image Error Codes](errorcode-image.md). 884 885| ID| Error Message| 886| ------- | --------------------------------------------| 887| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. | 888| 501 | Resource Unavailable. | 889 890**Example** 891 892```ts 893import { BusinessError } from '@kit.BasicServicesKit'; 894 895async function Demo() { 896 let rate : number = 0.5; 897 if (pixelMap != undefined) { 898 pixelMap.opacitySync(rate); 899 } 900} 901``` 902 903### createAlphaPixelmap 904 905createAlphaPixelmap(): Promise\<PixelMap> 906 907Creates a **PixelMap** object that contains only the alpha channel information. This object can be used for the shadow effect. This API uses a promise to return the result. 908 909**Atomic service API**: This API can be used in atomic services since API version 12. 910 911**System capability**: SystemCapability.Multimedia.Image.Core 912 913**Return value** 914 915| Type | Description | 916| -------------------------------- | --------------------------- | 917| Promise\<[PixelMap](#pixelmap)> | Promise used to return the **PixelMap** object.| 918 919**Example** 920 921```ts 922import { BusinessError } from '@kit.BasicServicesKit'; 923 924async function Demo() { 925 if (pixelMap != undefined) { 926 pixelMap.createAlphaPixelmap().then((alphaPixelMap: sendableImage.PixelMap) => { 927 console.info('Succeeded in creating alpha pixelmap.'); 928 }).catch((error: BusinessError) => { 929 console.error(`Failed to create alpha pixelmap. code is ${error.code}, message is ${error.message}`); 930 }) 931 } 932} 933``` 934 935### createAlphaPixelmapSync 936 937createAlphaPixelmapSync(): PixelMap 938 939Creates a **PixelMap** object that contains only the alpha channel information. This object can be used for the shadow effect. This API returns the result synchronously. 940 941**Atomic service API**: This API can be used in atomic services since API version 12. 942 943**System capability**: SystemCapability.Multimedia.Image.Core 944 945**Return value** 946 947| Type | Description | 948| -------------------------------- | --------------------- | 949| [PixelMap](#pixelmap) | Returns a **PixelMap** object if the operation is successful; throws an error otherwise.| 950 951**Error codes** 952 953For details about the error codes, see [Image Error Codes](errorcode-image.md). 954 955| ID| Error Message| 956| ------- | --------------------------------------------| 957| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. | 958| 501 | Resource Unavailable. | 959 960**Example** 961 962```ts 963import { BusinessError } from '@kit.BasicServicesKit'; 964 965async function Demo() { 966 let resPixelMap : sendableImage.PixelMap = pixelMap.createAlphaPixelmapSync(); 967 return resPixelMap; 968} 969``` 970 971### scale 972 973scale(x: number, y: number): Promise\<void> 974 975Scales this image based on a given width and height. This API uses a promise to return the result. 976 977**Atomic service API**: This API can be used in atomic services since API version 12. 978 979**System capability**: SystemCapability.Multimedia.Image.Core 980 981**Parameters** 982 983| Name| Type | Mandatory| Description | 984| ------ | ------ | ---- | ------------------------------- | 985| x | number | Yes | Scaling multiple of the width.| 986| y | number | Yes | Scaling multiple of the height.| 987 988**Return value** 989 990| Type | Description | 991| -------------- | --------------------------- | 992| Promise\<void> | Promise used to return the result.| 993 994**Example** 995 996```ts 997import { BusinessError } from '@kit.BasicServicesKit'; 998 999async function Demo() { 1000 let scaleX: number = 2.0; 1001 let scaleY: number = 1.0; 1002 if (pixelMap != undefined) { 1003 pixelMap.scale(scaleX, scaleY).then(() => { 1004 console.info('Succeeded in scaling pixelmap.'); 1005 }).catch((err: BusinessError) => { 1006 console.error(`Failed to scale pixelmap. code is ${err.code}, message is ${err.message}`); 1007 1008 }) 1009 } 1010} 1011``` 1012 1013### scaleSync 1014 1015scaleSync(x: number, y: number): void 1016 1017Scales this image based on a given width and height. This API returns the result synchronously. 1018 1019**Atomic service API**: This API can be used in atomic services since API version 12. 1020 1021**System capability**: SystemCapability.Multimedia.Image.Core 1022 1023**Parameters** 1024 1025| Name| Type | Mandatory| Description | 1026| ------ | ------ | ---- | ------------------------------- | 1027| x | number | Yes | Scaling multiple of the width.| 1028| y | number | Yes | Scaling multiple of the height.| 1029 1030**Error codes** 1031 1032For details about the error codes, see [Image Error Codes](errorcode-image.md). 1033 1034| ID| Error Message| 1035| ------- | --------------------------------------------| 1036| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. | 1037| 501 | Resource Unavailable. | 1038 1039**Example** 1040 1041```ts 1042import { BusinessError } from '@kit.BasicServicesKit'; 1043 1044async function Demo() { 1045 let scaleX: number = 2.0; 1046 let scaleY: number = 1.0; 1047 if (pixelMap != undefined) { 1048 pixelMap.scaleSync(scaleX, scaleY); 1049 } 1050} 1051``` 1052 1053### translate 1054 1055translate(x: number, y: number): Promise\<void> 1056 1057Translates this image based on given coordinates. This API uses a promise to return the result. 1058 1059**Atomic service API**: This API can be used in atomic services since API version 12. 1060 1061**System capability**: SystemCapability.Multimedia.Image.Core 1062 1063**Parameters** 1064 1065| Name| Type | Mandatory| Description | 1066| ------ | ------ | ---- | ----------- | 1067| x | number | Yes | X coordinate to translate.| 1068| y | number | Yes | Y coordinate to translate.| 1069 1070**Return value** 1071 1072| Type | Description | 1073| -------------- | --------------------------- | 1074| Promise\<void> | Promise used to return the result.| 1075 1076**Example** 1077 1078```ts 1079import { BusinessError } from '@kit.BasicServicesKit'; 1080 1081async function Demo() { 1082 let translateX: number = 50.0; 1083 let translateY: number = 10.0; 1084 if (pixelMap != undefined) { 1085 pixelMap.translate(translateX, translateY).then(() => { 1086 console.info('Succeeded in translating pixelmap.'); 1087 }).catch((err: BusinessError) => { 1088 console.error(`Failed to translate pixelmap. code is ${err.code}, message is ${err.message}`); 1089 }) 1090 } 1091} 1092``` 1093 1094### translateSync 1095 1096translateSync(x: number, y: number): void 1097 1098Translates this image based on given coordinates. This API returns the result synchronously. 1099 1100**Atomic service API**: This API can be used in atomic services since API version 12. 1101 1102**System capability**: SystemCapability.Multimedia.Image.Core 1103 1104**Parameters** 1105 1106| Name | Type | Mandatory| Description | 1107| -------- | -------------------- | ---- | ------------------------------- | 1108| x | number | Yes | Scaling multiple of the width.| 1109| y | number | Yes | Scaling multiple of the height.| 1110 1111**Error codes** 1112 1113For details about the error codes, see [Image Error Codes](errorcode-image.md). 1114 1115| ID| Error Message| 1116| ------- | --------------------------------------------| 1117| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. | 1118| 501 | Resource Unavailable. | 1119 1120**Example** 1121 1122```ts 1123import { BusinessError } from '@kit.BasicServicesKit'; 1124 1125async function Demo() { 1126 let translateX : number = 50.0; 1127 let translateY : number = 10.0; 1128 if (pixelMap != undefined) { 1129 pixelMap.translateSync(translateX, translateY); 1130 } 1131} 1132``` 1133 1134### rotate 1135 1136rotate(angle: number): Promise\<void> 1137 1138Rotates this image based on a given angle. This API uses a promise to return the result. 1139 1140**Atomic service API**: This API can be used in atomic services since API version 12. 1141 1142**System capability**: SystemCapability.Multimedia.Image.Core 1143 1144**Parameters** 1145 1146| Name| Type | Mandatory| Description | 1147| ------ | ------ | ---- | ----------------------------- | 1148| angle | number | Yes | Angle to rotate. | 1149 1150**Return value** 1151 1152| Type | Description | 1153| -------------- | --------------------------- | 1154| Promise\<void> | Promise used to return the result.| 1155 1156**Example** 1157 1158```ts 1159import { BusinessError } from '@kit.BasicServicesKit'; 1160 1161async function Demo() { 1162 let angle: number = 90.0; 1163 if (pixelMap != undefined) { 1164 pixelMap.rotate(angle).then(() => { 1165 console.info('Succeeded in rotating pixelmap.'); 1166 }).catch((err: BusinessError) => { 1167 console.error(`Failed to rotate pixelmap. code is ${err.code}, message is ${err.message}`); 1168 }) 1169 } 1170} 1171``` 1172 1173### rotateSync 1174 1175rotateSync(angle: number): void 1176 1177Rotates this image based on a given angle. This API returns the result synchronously. 1178 1179**Atomic service API**: This API can be used in atomic services since API version 12. 1180 1181**System capability**: SystemCapability.Multimedia.Image.Core 1182 1183**Parameters** 1184 1185| Name | Type | Mandatory| Description | 1186| -------- | -------------------- | ---- | ----------------------------- | 1187| angle | number | Yes | Angle to rotate. | 1188 1189**Error codes** 1190 1191For details about the error codes, see [Image Error Codes](errorcode-image.md). 1192 1193| ID| Error Message| 1194| ------- | --------------------------------------------| 1195| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. | 1196| 501 | Resource Unavailable. | 1197 1198**Example** 1199 1200```ts 1201import { BusinessError } from '@kit.BasicServicesKit'; 1202 1203async function Demo() { 1204 let angle : number = 90.0; 1205 if (pixelMap != undefined) { 1206 pixelMap.rotateSync(angle); 1207 } 1208} 1209``` 1210 1211### flip 1212 1213flip(horizontal: boolean, vertical: boolean): Promise\<void> 1214 1215Flips this image horizontally or vertically, or both. This API uses a promise to return the result. 1216 1217**Atomic service API**: This API can be used in atomic services since API version 12. 1218 1219**System capability**: SystemCapability.Multimedia.Image.Core 1220 1221**Parameters** 1222 1223| Name | Type | Mandatory| Description | 1224| ---------- | ------- | ---- | --------- | 1225| horizontal | boolean | Yes | Whether to flip the image horizontally.| 1226| vertical | boolean | Yes | Whether to flip the image vertically.| 1227 1228**Return value** 1229 1230| Type | Description | 1231| -------------- | --------------------------- | 1232| Promise\<void> | Promise used to return the result.| 1233 1234**Example** 1235 1236```ts 1237import { BusinessError } from '@kit.BasicServicesKit'; 1238 1239async function Demo() { 1240 let horizontal: boolean = true; 1241 let vertical: boolean = false; 1242 if (pixelMap != undefined) { 1243 pixelMap.flip(horizontal, vertical).then(() => { 1244 console.info('Succeeded in flipping pixelmap.'); 1245 }).catch((err: BusinessError) => { 1246 console.error(`Failed to flip pixelmap. code is ${err.code}, message is ${err.message}`); 1247 1248 }) 1249 } 1250} 1251``` 1252 1253### flipSync 1254 1255flipSync(horizontal: boolean, vertical: boolean): void 1256 1257Flips this image horizontally or vertically, or both. This API returns the result synchronously. 1258 1259**Atomic service API**: This API can be used in atomic services since API version 12. 1260 1261**System capability**: SystemCapability.Multimedia.Image.Core 1262 1263**Parameters** 1264 1265| Name | Type | Mandatory| Description | 1266| ---------- | -------------------- | ---- | ----------------------------- | 1267| horizontal | boolean | Yes | Whether to flip the image horizontally. | 1268| vertical | boolean | Yes | Whether to flip the image vertically. | 1269 1270**Error codes** 1271 1272For details about the error codes, see [Image Error Codes](errorcode-image.md). 1273 1274| ID| Error Message| 1275| ------- | --------------------------------------------| 1276| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. | 1277| 501 | Resource Unavailable. | 1278 1279**Example** 1280 1281```ts 1282import { BusinessError } from '@kit.BasicServicesKit'; 1283 1284async function Demo() { 1285 let horizontal : boolean = true; 1286 let vertical : boolean = false; 1287 if (pixelMap != undefined) { 1288 pixelMap.flipSync(horizontal, vertical); 1289 } 1290} 1291``` 1292 1293### crop 1294 1295crop(region: image.Region): Promise\<void> 1296 1297Crops this image based on a given size. This API uses a promise to return the result. 1298 1299**Atomic service API**: This API can be used in atomic services since API version 12. 1300 1301**System capability**: SystemCapability.Multimedia.Image.Core 1302 1303**Parameters** 1304 1305| Name| Type | Mandatory| Description | 1306| ------ | ------------------ | ---- | ----------- | 1307| region | [Region](../apis-image-kit/js-apis-image.md#region8) | Yes | Size of the image after cropping.| 1308 1309**Return value** 1310 1311| Type | Description | 1312| -------------- | --------------------------- | 1313| Promise\<void> | Promise used to return the result.| 1314 1315**Example** 1316 1317```ts 1318import { image } from '@kit.ImageKit'; 1319import { BusinessError } from '@kit.BasicServicesKit'; 1320 1321async function Demo() { 1322 let region: image.Region = { x: 0, y: 0, size: { height: 100, width: 100 } }; 1323 if (pixelMap != undefined) { 1324 pixelMap.crop(region).then(() => { 1325 console.info('Succeeded in cropping pixelmap.'); 1326 }).catch((err: BusinessError) => { 1327 console.error(`Failed to crop pixelmap. code is ${err.code}, message is ${err.message}`); 1328 1329 }); 1330 } 1331} 1332``` 1333 1334### cropSync 1335 1336cropSync(region: image.Region): void 1337 1338Crops this image based on a given size. This API returns the result synchronously. 1339 1340**Atomic service API**: This API can be used in atomic services since API version 12. 1341 1342**System capability**: SystemCapability.Multimedia.Image.Core 1343 1344**Parameters** 1345 1346| Name | Type | Mandatory| Description | 1347| -------- | -------------------- | ---- | ----------------------------- | 1348| region | [Region](../apis-image-kit/js-apis-image.md#region8) | Yes | Size of the image after cropping. | 1349 1350**Error codes** 1351 1352For details about the error codes, see [Image Error Codes](errorcode-image.md). 1353 1354| ID| Error Message| 1355| ------- | --------------------------------------------| 1356| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. | 1357| 501 | Resource Unavailable. | 1358 1359**Example** 1360 1361```ts 1362import { image } from '@kit.ImageKit'; 1363import { BusinessError } from '@kit.BasicServicesKit'; 1364 1365async function Demo() { 1366 let region : image.Region = { x: 0, y: 0, size: { height: 100, width: 100 } }; 1367 if (pixelMap != undefined) { 1368 pixelMap.cropSync(region); 1369 } 1370} 1371``` 1372 1373### getColorSpace 1374 1375getColorSpace(): colorSpaceManager.ColorSpaceManager 1376 1377Obtains the color space of this image. 1378 1379**System capability**: SystemCapability.Multimedia.Image.Core 1380 1381**Return value** 1382 1383| Type | Description | 1384| ----------------------------------- | ---------------- | 1385| [colorSpaceManager.ColorSpaceManager](../apis-arkgraphics2d/js-apis-colorSpaceManager.md#colorspacemanager) | Color space.| 1386 1387**Error codes** 1388 1389For details about the error codes, see [Image Error Codes](errorcode-image.md). 1390 1391| ID| Error Message| 1392| ------- | --------------------------------------------| 1393| 62980101| If the image data abnormal. | 1394| 62980103| If the image data unsupport. | 1395| 62980115| If the image parameter invalid. | 1396 1397**Example** 1398 1399```ts 1400async function Demo() { 1401 if (pixelMap != undefined) { 1402 let csm = pixelMap.getColorSpace(); 1403 } 1404} 1405``` 1406 1407### setColorSpace 1408 1409setColorSpace(colorSpace: colorSpaceManager.ColorSpaceManager): void 1410 1411Sets the color space for this image. 1412 1413**System capability**: SystemCapability.Multimedia.Image.Core 1414 1415**Parameters** 1416 1417| Name | Type | Mandatory| Description | 1418| ---------- | ----------------------------------- | ---- | --------------- | 1419| colorSpace | [colorSpaceManager.ColorSpaceManager](../apis-arkgraphics2d/js-apis-colorSpaceManager.md#colorspacemanager) | Yes | Color space.| 1420 1421**Error codes** 1422 1423For details about the error codes, see [Image Error Codes](errorcode-image.md). 1424 1425| ID| Error Message| 1426| ------- | --------------------------------------------| 1427| 62980111| If the operation invalid. | 1428| 62980115| If the image parameter invalid. | 1429 1430**Example** 1431 1432```ts 1433import { colorSpaceManager } from '@kit.ArkGraphics2D'; 1434async function Demo() { 1435 let colorSpaceName = colorSpaceManager.ColorSpace.SRGB; 1436 let csm: colorSpaceManager.ColorSpaceManager = colorSpaceManager.create(colorSpaceName); 1437 if (pixelMap != undefined) { 1438 pixelMap.setColorSpace(csm); 1439 } 1440} 1441``` 1442 1443### applyColorSpace 1444 1445applyColorSpace(targetColorSpace: colorSpaceManager.ColorSpaceManager): Promise\<void> 1446 1447Performs Color Space Converters (CSC) on the image pixel color based on a given color space. This API uses a promise to return the result. 1448 1449**System capability**: SystemCapability.Multimedia.Image.Core 1450 1451**Parameters** 1452 1453| Name| Type | Mandatory| Description | 1454| ------ | ------------------ | ---- | ----------- | 1455| targetColorSpace | [colorSpaceManager.ColorSpaceManager](../apis-arkgraphics2d/js-apis-colorSpaceManager.md#colorspacemanager) | Yes | Target color space. SRGB, DCI_P3, DISPLAY_P3, and ADOBE_RGB_1998 are supported.| 1456 1457**Return value** 1458 1459| Type | Description | 1460| -------------- | --------------------------- | 1461| Promise\<void> | Promise used to return the result.| 1462 1463**Error codes** 1464 1465For details about the error codes, see [Image Error Codes](errorcode-image.md). 1466 1467| ID| Error Message| 1468| ------- | ------------------------------------------| 1469| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. | 1470| 62980104| Failed to initialize the internal object. | 1471| 62980108| Failed to convert the color space. | 1472| 62980115| Invalid image parameter. | 1473 1474**Example** 1475 1476```ts 1477import { colorSpaceManager } from '@kit.ArkGraphics2D'; 1478import { BusinessError } from '@kit.BasicServicesKit'; 1479 1480async function Demo() { 1481 let colorSpaceName = colorSpaceManager.ColorSpace.SRGB; 1482 let targetColorSpace: colorSpaceManager.ColorSpaceManager = colorSpaceManager.create(colorSpaceName); 1483 pixelMap.applyColorSpace(targetColorSpace).then(() => { 1484 console.info('Succeeded in applying color space for pixelmap object.'); 1485 }).catch((error: BusinessError) => { 1486 console.error(`Failed to apply color space for pixelmap object. code is ${error.code}, message is ${error.message}`); 1487 }) 1488} 1489``` 1490 1491### marshalling 1492 1493marshalling(sequence: rpc.MessageSequence): void 1494 1495Marshals this **PixelMap** object and writes it to a **MessageSequence** object. 1496 1497**System capability**: SystemCapability.Multimedia.Image.Core 1498 1499**Parameters** 1500 1501| Name | Type | Mandatory| Description | 1502| ---------------------- | ------------------------------------------------------ | ---- | ---------------------------------------- | 1503| sequence | [rpc.MessageSequence](../apis-ipc-kit/js-apis-rpc.md#messagesequence9) | Yes | **MessageSequence** object. | 1504 1505**Error codes** 1506 1507For details about the error codes, see [Image Error Codes](errorcode-image.md). 1508 1509| ID| Error Message| 1510| ------- | --------------------------------------------| 1511| 62980115 | Invalid image parameter. | 1512| 62980097 | IPC error. | 1513 1514**Example** 1515```ts 1516import { sendableImage } from '@kit.ImageKit'; 1517import { image } from '@kit.ImageKit'; 1518import { rpc } from '@kit.IPCKit'; 1519 1520class MySequence implements rpc.Parcelable { 1521 pixel_map: sendableImage.PixelMap; 1522 constructor(conPixelMap : sendableImage.PixelMap) { 1523 this.pixel_map = conPixelMap; 1524 } 1525 marshalling(messageSequence : rpc.MessageSequence) { 1526 this.pixel_map.marshalling(messageSequence); 1527 console.info('marshalling'); 1528 return true; 1529 } 1530 unmarshalling(messageSequence : rpc.MessageSequence) { 1531 sendableImage.createPixelMap(new ArrayBuffer(96), {size: { height:4, width: 6}}).then((pixelParcel: sendableImage.PixelMap) => { 1532 pixelParcel.unmarshalling(messageSequence).then(async (pixelMap: sendableImage.PixelMap) => { 1533 this.pixel_map = pixelMap; 1534 pixelMap.getImageInfo().then((imageInfo: image.ImageInfo) => { 1535 console.info("unmarshalling information h:" + imageInfo.size.height + "w:" + imageInfo.size.width); 1536 }) 1537 }) 1538 }); 1539 return true; 1540 } 1541} 1542async function Demo() { 1543 const color: ArrayBuffer = new ArrayBuffer(96); 1544 let bufferArr: Uint8Array = new Uint8Array(color); 1545 for (let i = 0; i < bufferArr.length; i++) { 1546 bufferArr[i] = 0x80; 1547 } 1548 let opts: image.InitializationOptions = { 1549 editable: true, 1550 pixelFormat: 4, 1551 size: { height: 4, width: 6 }, 1552 alphaType: 3 1553 } 1554 let pixelMap: sendableImage.PixelMap | undefined = undefined; 1555 sendableImage.createPixelMap(color, opts).then((srcPixelMap: sendableImage.PixelMap) => { 1556 pixelMap = srcPixelMap; 1557 }) 1558 if (pixelMap != undefined) { 1559 // Implement serialization. 1560 let parcelable: MySequence = new MySequence(pixelMap); 1561 let data: rpc.MessageSequence = rpc.MessageSequence.create(); 1562 data.writeParcelable(parcelable); 1563 1564 // Implement deserialization to obtain data through the RPC. 1565 let ret: MySequence = new MySequence(pixelMap); 1566 data.readParcelable(ret); 1567 } 1568} 1569``` 1570 1571### unmarshalling 1572 1573unmarshalling(sequence: rpc.MessageSequence): Promise\<PixelMap> 1574 1575Unmarshals a **MessageSequence** object to obtain a **PixelMap** object. 1576To create a **PixelMap** object in synchronous mode, use [createPixelMapFromParcel](#sendableimagecreatepixelmapfromparcel). 1577 1578**System capability**: SystemCapability.Multimedia.Image.Core 1579 1580**Parameters** 1581 1582| Name | Type | Mandatory| Description | 1583| ---------------------- | ----------------------------------------------------- | ---- | ---------------------------------------- | 1584| sequence | [rpc.MessageSequence](../apis-ipc-kit/js-apis-rpc.md#messagesequence9) | Yes | **MessageSequence** object that stores the **PixelMap** information. | 1585 1586**Return value** 1587 1588| Type | Description | 1589| -------------------------------- | --------------------- | 1590| Promise\<[PixelMap](#pixelmap)> | Promise used to return the result. If the operation fails, an error message is returned.| 1591 1592**Error codes** 1593 1594For details about the error codes, see [Image Error Codes](errorcode-image.md). 1595 1596| ID| Error Message| 1597| ------- | --------------------------------------------| 1598| 62980115 | Invalid image parameter. | 1599| 62980097 | IPC error. | 1600| 62980096 | The operation failed. | 1601 1602**Example** 1603 1604```ts 1605import { sendableImage } from '@kit.ImageKit'; 1606import { image } from '@kit.ImageKit'; 1607import { rpc } from '@kit.IPCKit'; 1608 1609class MySequence implements rpc.Parcelable { 1610 pixel_map: sendableImage.PixelMap; 1611 constructor(conPixelMap: sendableImage.PixelMap) { 1612 this.pixel_map = conPixelMap; 1613 } 1614 marshalling(messageSequence: rpc.MessageSequence) { 1615 this.pixel_map.marshalling(messageSequence); 1616 console.info('marshalling'); 1617 return true; 1618 } 1619 unmarshalling(messageSequence: rpc.MessageSequence) { 1620 sendableImage.createPixelMap(new ArrayBuffer(96), {size: { height:4, width: 6}}).then((pixelParcel : sendableImage.PixelMap) => { 1621 pixelParcel.unmarshalling(messageSequence).then(async (pixelMap : sendableImage.PixelMap) => { 1622 this.pixel_map = pixelMap; 1623 pixelMap.getImageInfo().then((imageInfo : image.ImageInfo) => { 1624 console.info("unmarshalling information h:" + imageInfo.size.height + "w:" + imageInfo.size.width); 1625 }) 1626 }) 1627 }); 1628 return true; 1629 } 1630} 1631async function Demo() { 1632 const color: ArrayBuffer = new ArrayBuffer(96); 1633 let bufferArr: Uint8Array = new Uint8Array(color); 1634 for (let i = 0; i < bufferArr.length; i++) { 1635 bufferArr[i] = 0x80; 1636 } 1637 let opts: image.InitializationOptions = { 1638 editable: true, 1639 pixelFormat: 4, 1640 size: { height: 4, width: 6 }, 1641 alphaType: 3 1642 } 1643 let pixelMap: sendableImage.PixelMap | undefined = undefined; 1644 sendableImage.createPixelMap(color, opts).then((srcPixelMap : sendableImage.PixelMap) => { 1645 pixelMap = srcPixelMap; 1646 }) 1647 if (pixelMap != undefined) { 1648 // Implement serialization. 1649 let parcelable: MySequence = new MySequence(pixelMap); 1650 let data : rpc.MessageSequence = rpc.MessageSequence.create(); 1651 data.writeParcelable(parcelable); 1652 1653 // Implement deserialization to obtain data through the RPC. 1654 let ret : MySequence = new MySequence(pixelMap); 1655 data.readParcelable(ret); 1656 } 1657} 1658``` 1659 1660### release 1661 1662release():Promise\<void> 1663 1664Releases this **PixelMap** object. This API uses a promise to return the result. 1665 1666**Atomic service API**: This API can be used in atomic services since API version 12. 1667 1668**System capability**: SystemCapability.Multimedia.Image.Core 1669 1670**Return value** 1671 1672| Type | Description | 1673| -------------- | ------------------------------- | 1674| Promise\<void> | Promise used to return the result.| 1675 1676**Example** 1677 1678```ts 1679import { BusinessError } from '@kit.BasicServicesKit'; 1680 1681async function Demo() { 1682 if (pixelMap != undefined) { 1683 pixelMap.release().then(() => { 1684 console.info('Succeeded in releasing pixelmap object.'); 1685 }).catch((error: BusinessError) => { 1686 console.error(`Failed to release pixelmap object. code is ${error.code}, message is ${error.message}`); 1687 }) 1688 } 1689} 1690``` 1691 1692## Size 1693 1694Describes the size of an image. 1695It inherits from [lang.ISendable](../../arkts-utils/arkts-sendable.md#isendable). 1696 1697**Widget capability**: This API can be used in ArkTS widgets since API version 12. 1698 1699**Atomic service API**: This API can be used in atomic services since API version 12. 1700 1701**System capability**: SystemCapability.Multimedia.Image.Core 1702 1703| Name | Type | Read Only| Optional| Description | 1704| ------ | ------ | ---- | ---- | -------------- | 1705| height | number | No | No | Height of the output image, in px.| 1706| width | number | No | No | Width of the output image, in px.| 1707 1708## Region 1709 1710Describes the region information. 1711It inherits from [lang.ISendable](../../arkts-utils/arkts-sendable.md#isendable). 1712 1713**Widget capability**: This API can be used in ArkTS widgets since API version 12. 1714 1715**Atomic service API**: This API can be used in atomic services since API version 12. 1716 1717**System capability**: SystemCapability.Multimedia.Image.Core 1718 1719| Name| Type | Read Only| Optional| Description | 1720| ---- | ------------- | ---- | ---- | ------------ | 1721| size | [Size](#size) | No | No | Region size. | 1722| x | number | No | No | X coordinate.| 1723| y | number | No | No | Y coordinate.| 1724 1725## sendableImage.createImageSource 1726 1727createImageSource(uri: string): ImageSource 1728 1729Creates an **ImageSource** instance based on a given URI. 1730 1731 1732**Atomic service API**: This API can be used in atomic services since API version 12. 1733 1734**System capability**: SystemCapability.Multimedia.Image.ImageSource 1735 1736**Parameters** 1737 1738| Name| Type | Mandatory| Description | 1739| ------ | ------ | ---- | ---------------------------------- | 1740| uri | string | Yes | Image path. Currently, only the application sandbox path is supported.<br>The following formats are supported: .jpg, .png, .gif, .bmp, .webp, .dng [SVG](./js-apis-image.md#svg), and ico.| 1741 1742**Return value** 1743 1744| Type | Description | 1745| --------------------------- | -------------------------------------------- | 1746| [ImageSource](#imagesource) | Returns the **ImageSource** instance if the operation is successful; returns **undefined** otherwise.| 1747 1748**Example** 1749 1750```ts 1751const context: Context = getContext(this); 1752const path: string = context.cacheDir + "/test.jpg"; 1753const sendableImageSourceApi: sendableImage.ImageSource = sendableImage.createImageSource(path); 1754``` 1755 1756## sendableImage.createImageSource 1757 1758createImageSource(fd: number): ImageSource 1759 1760Creates an **ImageSource** instance based on a given file descriptor. 1761 1762**Atomic service API**: This API can be used in atomic services since API version 12. 1763 1764**System capability**: SystemCapability.Multimedia.Image.ImageSource 1765 1766**Parameters** 1767 1768| Name| Type | Mandatory| Description | 1769| ------ | ------ | ---- | ------------- | 1770| fd | number | Yes | File descriptor.| 1771 1772**Return value** 1773 1774| Type | Description | 1775| --------------------------- | -------------------------------------------- | 1776| [ImageSource](#imagesource) | Returns the **ImageSource** instance if the operation is successful; returns **undefined** otherwise.| 1777 1778**Example** 1779 1780```ts 1781import { fileIo as fs } from '@kit.CoreFileKit'; 1782 1783const context: Context = getContext(this); 1784const path: string = context.cacheDir + "/test.jpg"; 1785let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 1786const sendableImageSourceApi: sendableImage.ImageSource = sendableImage.createImageSource(file.fd); 1787``` 1788 1789## sendableImage.createImageSource 1790 1791createImageSource(buf: ArrayBuffer): ImageSource 1792 1793Creates an **ImageSource** instance based on buffers. 1794 1795**Widget capability**: This API can be used in ArkTS widgets since API version 12. 1796 1797**Atomic service API**: This API can be used in atomic services since API version 12. 1798 1799**System capability**: SystemCapability.Multimedia.Image.ImageSource 1800 1801**Parameters** 1802 1803| Name| Type | Mandatory| Description | 1804| ------ | ----------- | ---- | ---------------- | 1805| buf | ArrayBuffer | Yes | Array of image buffers.| 1806 1807**Return value** 1808 1809| Type | Description | 1810| --------------------------- | -------------------------------------------- | 1811| [ImageSource](#imagesource) | Returns the **ImageSource** instance if the operation is successful; returns **undefined** otherwise.| 1812 1813 1814**Example** 1815 1816```ts 1817const buf: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4. 1818const sendableImageSourceApi: sendableImage.ImageSource = sendableImage.createImageSource(buf); 1819``` 1820 1821## sendableImage.createImageReceiver 1822 1823createImageReceiver(size: image.Size, format: image.ImageFormat, capacity: number): ImageReceiver 1824 1825Creates an **ImageReceiver** instance based on the specified image size, format, and capacity. 1826 1827**System capability**: SystemCapability.Multimedia.Image.ImageReceiver 1828 1829**Parameters** 1830 1831| Name | Type | Mandatory| Description | 1832| -------- | ------ | ---- | ---------------------- | 1833| size | [image.Size](./js-apis-image.md#size) | Yes | Default size of the image. | 1834| format | [image.ImageFormat](./js-apis-image.md#imageformat9) | Yes | Image format, which is a constant of **image.ImageFormat**. (Currently, only **ImageFormat:JPEG** is supported.) | 1835| capacity | number | Yes | Maximum number of images that can be accessed at the same time.| 1836 1837**Return value** 1838 1839| Type | Description | 1840| -------------------------------- | --------------------------------------- | 1841| [ImageReceiver](#imagereceiver) | Returns an **ImageReceiver** instance if the operation is successful.| 1842 1843**Error codes** 1844 1845For details about the error codes, see [Image Error Codes](errorcode-image.md). 1846 1847| ID| Error Message| 1848| ------- | --------------------------------------------| 1849| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. | 1850 1851**Example** 1852 1853```ts 1854import { image } from '@kit.ImageKit'; 1855 1856let size: image.Size = { 1857 height: 8192, 1858 width: 8 1859} 1860let receiver: sendableImage.ImageReceiver = sendableImage.createImageReceiver(size, image.ImageFormat.JPEG, 8); 1861``` 1862 1863## ImageSource 1864 1865Provides APIs to obtain image information. Before calling any API in **ImageSource**, you must use [createImageSource](#sendableimagecreateimagesource) to create an **ImageSource** instance. 1866 1867 1868### createPixelMap 1869 1870createPixelMap(options?: image.DecodingOptions): Promise\<PixelMap> 1871 1872Creates a **PixelMap** object based on image decoding parameters. This API uses a promise to return the result. 1873 1874**Widget capability**: This API can be used in ArkTS widgets since API version 12. 1875 1876**Atomic service API**: This API can be used in atomic services since API version 12. 1877 1878**System capability**: SystemCapability.Multimedia.Image.ImageSource 1879 1880**Parameters** 1881 1882| Name | Type | Mandatory| Description | 1883| ------- | ------------------------------------ | ---- | ---------- | 1884| options | [image.DecodingOptions](./js-apis-image.md#decodingoptions7) | No | Image decoding parameters.| 1885 1886**Return value** 1887 1888| Type | Description | 1889| -------------------------------- | --------------------- | 1890| Promise\<[PixelMap]> | Promise used to return the **PixelMap** object.| 1891 1892**Example** 1893 1894```ts 1895import { BusinessError } from '@kit.BasicServicesKit'; 1896 1897const context: Context = getContext(this); 1898const path: string = context.cacheDir + "/test.jpg"; 1899const sendableImageSourceApi: sendableImage.ImageSource = sendableImage.createImageSource(path); 1900sendableImageSourceApi.createPixelMap().then((pixelMap: sendableImage.PixelMap) => { 1901 console.info('Succeeded in creating pixelMap object through image decoding parameters.'); 1902}).catch((error: BusinessError) => { 1903 console.error(`Failed to create pixelMap object through image decoding parameters. code ${error.code}, message is ${error.message}`); 1904}) 1905``` 1906 1907### release 1908 1909release(): Promise\<void> 1910 1911Releases this **ImageSource** instance. This API uses a promise to return the result. 1912 1913The thread that runs **release** is insecure. 1914 1915**System capability**: SystemCapability.Multimedia.Image.ImageSource 1916 1917**Return value** 1918 1919| Type | Description | 1920| -------------- | --------------------------- | 1921| Promise\<void> | Promise used to return the result.| 1922 1923**Example** 1924 1925```ts 1926import { BusinessError } from '@kit.BasicServicesKit'; 1927 1928const context: Context = getContext(this); 1929const path: string = context.cacheDir + "/test.jpg"; 1930const sendableImageSourceApi: sendableImage.ImageSource = sendableImage.createImageSource(path); 1931sendableImageSourceApi.release().then(() => { 1932 console.info('Succeeded in releasing the image source instance.'); 1933}).catch((error: BusinessError) => { 1934 console.error(`Failed to release the image source instance. code ${error.code}, message is ${error.message}`); 1935}) 1936``` 1937 1938## Image 1939 1940Provides APIs for basic image operations, including obtaining image information and reading and writing image data. An **Image** instance is returned when [readNextImage](#readnextimage) and [readLatestImage](#readlatestimage) are called. 1941This class inherits from [lang.ISendable](../../arkts-utils/arkts-sendable.md#isendable). 1942 1943### Attributes 1944 1945**System capability**: SystemCapability.Multimedia.Image.Core 1946 1947| Name | Type | Read Only| Optional| Description | 1948| -------- | ------------------ | ---- | ---- | -------------------------------------------------- | 1949| clipRect | [Region](#region) | No | No | Image area to be cropped. | 1950| size | [Size](#size) | Yes | No | Image size. If the **image** object stores the camera preview stream data (YUV image data), the width and height in **size** obtained correspond to those of the YUV image. If the **image** object stores the camera photo stream data (JPEG image data, which is already encoded), the width in **size** obtained is the JPEG data size, and the height is 1. The type of data stored in the **image** object depends on whether the application passes the surface ID in the receiver to a **previewOutput** or **captureOutput** object of the camera. For details about the best practices of camera preview and photo capture, see [Dual-Channel Preview (ArkTS)](../../media/camera/camera-dual-channel-preview.md) and [Photo Capture Sample (ArkTS)](../../media/camera/camera-shooting-case.md). | 1951| format | number | Yes | No | Image format. For details, see [OH_NativeBuffer_Format](../apis-arkgraphics2d/_o_h___native_buffer.md#oh_nativebuffer_format).| 1952| timestamp<sup>12+</sup> | number | Yes | No | Image timestamp. Timestamps, measured in nanoseconds, are usually monotonically increasing. The specific meaning and baseline of these timestamps are determined by the image producer, which is the camera in the camera preview and photo scenarios. As a result, images from different producers may carry timestamps with distinct meanings and baselines, making direct comparison between them infeasible. To obtain the generation time of a photo, you can use [getImageProperty](js-apis-image.md#getimageproperty11) to read the related EXIF information.| 1953 1954### getComponent 1955 1956getComponent(componentType: image.ComponentType): Promise\<image.Component> 1957 1958Obtains the component buffer from the **Image** instance based on the color component type. This API uses a promise to return the result. 1959 1960The thread that runs **getComponent** is insecure. 1961 1962**System capability**: SystemCapability.Multimedia.Image.Core 1963 1964**Parameters** 1965 1966| Name | Type | Mandatory| Description | 1967| ------------- | -------------------------------- | ---- | ---------------- | 1968| componentType | [image.ComponentType](./js-apis-image.md#componenttype9) | Yes | Color component type of the image.| 1969 1970**Return value** 1971 1972| Type | Description | 1973| --------------------------------- | --------------------------------- | 1974| Promise<[image.Component](./js-apis-image.md#component9)> | Promise used to return the component buffer.| 1975 1976**Example** 1977 1978```ts 1979import { BusinessError } from '@kit.BasicServicesKit'; 1980import { image } from '@kit.ImageKit'; 1981 1982async function Demo() { 1983 let size: image.Size = { 1984 height: 8192, 1985 width: 8 1986 } 1987 let receiver: sendableImage.ImageReceiver = sendableImage.createImageReceiver(size, image.ImageFormat.JPEG, 8); 1988 let img = await receiver.readNextImage(); 1989 img.getComponent(4).then((component: image.Component) => { 1990 console.info('getComponent succeeded.'); 1991 }).catch((error: BusinessError) => { 1992 console.error(`getComponent failed code ${error.code}, message is ${error.message}`); 1993 }) 1994} 1995``` 1996 1997### release 1998 1999release(): Promise\<void> 2000 2001Releases this **Image** instance. This API uses a promise to return the result. 2002 2003The corresponding resources must be released before another image arrives. The thread that runs **release** is insecure. 2004 2005 2006**System capability**: SystemCapability.Multimedia.Image.Core 2007 2008**Return value** 2009 2010| Type | Description | 2011| -------------- | --------------------- | 2012| Promise\<void> | Promise used to return the result.| 2013 2014**Example** 2015 2016```ts 2017import { BusinessError } from '@kit.BasicServicesKit'; 2018import { image } from '@kit.ImageKit'; 2019 2020async function Demo() { 2021 let size: image.Size = { 2022 height: 8192, 2023 width: 8 2024 } 2025 let receiver: sendableImage.ImageReceiver = sendableImage.createImageReceiver(size, image.ImageFormat.JPEG, 8); 2026 let img = await receiver.readNextImage(); 2027 img.release().then(() => { 2028 console.info('release succeeded.'); 2029 }).catch((error: BusinessError) => { 2030 console.error(`release failed. code ${error.code}, message is ${error.message}`); 2031 }) 2032} 2033``` 2034 2035## ImageReceiver 2036 2037You can use the **ImageReceiver** class to obtain the surface ID of a component, read the latest image or the next image, and release **ImageReceiver** instances. 2038 2039Before calling any APIs in **ImageReceiver**, you must create an **ImageReceiver** instance. 2040 2041### Attributes 2042 2043**System capability**: SystemCapability.Multimedia.Image.ImageReceiver 2044 2045| Name | Type | Read Only| Optional| Description | 2046| -------- | ---------------------------- | ---- | ---- | ------------------ | 2047| size | [image.Size](./js-apis-image.md#size) | Yes | No | Image size. | 2048| capacity | number | Yes | No | Maximum number of images that can be accessed at the same time.| 2049| format | [image.ImageFormat](./js-apis-image.md#imageformat9) | Yes | No | Image format. | 2050 2051### getReceivingSurfaceId 2052 2053getReceivingSurfaceId(): Promise\<string> 2054 2055Obtains a surface ID for the camera or other components. This API uses a promise to return the result. 2056 2057**System capability**: SystemCapability.Multimedia.Image.ImageReceiver 2058 2059**Return value** 2060 2061| Type | Description | 2062| ---------------- | -------------------- | 2063| Promise\<string> | Promise used to return the surface ID.| 2064 2065**Example** 2066 2067```ts 2068import { BusinessError } from '@kit.BasicServicesKit'; 2069import { image } from '@kit.ImageKit'; 2070 2071let size: image.Size = { 2072 height: 8192, 2073 width: 8 2074} 2075let receiver: sendableImage.ImageReceiver = sendableImage.createImageReceiver(size, image.ImageFormat.JPEG, 8); 2076receiver.getReceivingSurfaceId().then((id: string) => { 2077 console.info('Succeeded in getting the ReceivingSurfaceId.'); 2078}).catch((error: BusinessError) => { 2079 console.error(`Failed to get the ReceivingSurfaceId.code ${error.code}, message is ${error.message}`); 2080}) 2081``` 2082 2083### readLatestImage 2084 2085readLatestImage(): Promise\<Image> 2086 2087Reads the latest image from the **ImageReceiver** instance. This API uses a promise to return the result. 2088 2089This API can be called to receive data only after the [on](#on) callback is triggered. When the [Image](#image) object returned by this API is no longer needed, call [release](#release-2) to release the object. New data can be received only after the release. 2090 2091**System capability**: SystemCapability.Multimedia.Image.ImageReceiver 2092 2093**Return value** 2094 2095| Type | Description | 2096| ------------------------- | ------------------ | 2097| Promise<[Image](#image)> | Promise used to return the latest image.| 2098 2099**Example** 2100 2101```ts 2102import { BusinessError } from '@kit.BasicServicesKit'; 2103import { image } from '@kit.ImageKit'; 2104 2105let size: image.Size = { 2106 height: 8192, 2107 width: 8 2108} 2109let receiver: sendableImage.ImageReceiver = sendableImage.createImageReceiver(size, image.ImageFormat.JPEG, 8); 2110receiver.readLatestImage().then((img: image.Image) => { 2111 console.info('readLatestImage succeeded.'); 2112}).catch((error: BusinessError) => { 2113 console.error(`readLatestImage failed. code ${error.code}, message is ${error.message}`); 2114}) 2115``` 2116 2117### readNextImage 2118 2119readNextImage(): Promise\<Image> 2120 2121Reads the next image from the **ImageReceiver** instance. This API uses a promise to return the result. 2122 2123This API can be called to receive data only after the [on](#on) callback is triggered. When the [Image](#image) object returned by this API is no longer needed, call [release](#release-2) to release the object. New data can be received only after the release. 2124 2125**System capability**: SystemCapability.Multimedia.Image.ImageReceiver 2126 2127**Return value** 2128 2129| Type | Description | 2130| ------------------------- | -------------------- | 2131| Promise<[Image](#image)> | Promise used to return the next image.| 2132 2133**Example** 2134 2135```ts 2136import { BusinessError } from '@kit.BasicServicesKit'; 2137import { image } from '@kit.ImageKit'; 2138 2139let size: image.Size = { 2140 height: 8192, 2141 width: 8 2142} 2143let receiver: sendableImage.ImageReceiver = sendableImage.createImageReceiver(size, image.ImageFormat.JPEG, 8); 2144receiver.readNextImage().then((img: image.Image) => { 2145 console.info('readNextImage succeeded.'); 2146}).catch((error: BusinessError) => { 2147 console.error(`readNextImage failed. code ${error.code}, message is ${error.message}`); 2148}) 2149``` 2150 2151### on 2152 2153on(type: 'imageArrival', callback: AsyncCallback\<void>): void 2154 2155Listens for image arrival events. 2156 2157**System capability**: SystemCapability.Multimedia.Image.ImageReceiver 2158 2159**Parameters** 2160 2161| Name | Type | Mandatory| Description | 2162| -------- | -------------------- | ---- | ------------------------------------------------------ | 2163| type | string | Yes | Type of event to listen for. The value is fixed at **'imageArrival'**, which is triggered when an image is received.| 2164| callback | AsyncCallback\<void> | Yes | Callback invoked for the event. | 2165 2166**Example** 2167 2168```ts 2169import { BusinessError } from '@kit.BasicServicesKit'; 2170import { image } from '@kit.ImageKit'; 2171 2172let size: image.Size = { 2173 height: 8192, 2174 width: 8 2175} 2176let receiver: sendableImage.ImageReceiver = sendableImage.createImageReceiver(size, image.ImageFormat.JPEG, 8); 2177receiver.on('imageArrival', () => { 2178 // image arrival, do something. 2179}) 2180``` 2181 2182### release 2183 2184release(): Promise\<void> 2185 2186Releases this **ImageReceiver** instance. This API uses a promise to return the result. 2187 2188The thread that runs **release** is insecure. 2189 2190**System capability**: SystemCapability.Multimedia.Image.ImageReceiver 2191 2192**Return value** 2193 2194| Type | Description | 2195| -------------- | ------------------ | 2196| Promise\<void> | Promise used to return the result.| 2197 2198**Example** 2199 2200```ts 2201import { BusinessError } from '@kit.BasicServicesKit'; 2202import { image } from '@kit.ImageKit'; 2203 2204let size: image.Size = { 2205 height: 8192, 2206 width: 8 2207} 2208let receiver: sendableImage.ImageReceiver = sendableImage.createImageReceiver(size, image.ImageFormat.JPEG, 8); 2209receiver.release().then(() => { 2210 console.info('release succeeded.'); 2211}).catch((error: BusinessError) => { 2212 console.error(`release failed. code ${error.code}, message is ${error.message}`); 2213}) 2214``` 2215