• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.multimedia.image (Image Processing)
2
3> **NOTE**
4>
5> - The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
6>
7> - Since API version 12, the APIs of this module are supported in ArkTS widgets.
8
9The module provides capabilities for image decoding, encoding, editing, metadata processing, and image receiving.
10
11This module contains the following classes:
12
13- [ImageSource](#imagesource): provides the capabilities of obtaining [image information](#imageinfo), decoding images to PixelMaps or Pictures, and reading and modifying [image properties](#propertykey7). [Supported image formats for decoding](#properties-2) include png, jpeg, bmp, gif, webp, dng, and heic<sup>12+</sup>.
14
15- [ImagePacker](#imagepacker): provides the capability of encoding images into compressed data streams or files. Encoding requires the ImageSource, PixelMap, or Picture of an image as the input. [Supported image formats for encoding](#properties-3) include jpeg, webp, png, heic<sup>12+</sup>, and gif<sup>18+</sup>.
16
17- [PixelMap](#pixelmap7): an object containing pixel data and [image information](#imageinfo). It can be used for reading/writing pixel data and performing operations such as cropping, scaling, translating, rotating, and mirroring. It can also be directly passed to the [Image component](../apis-arkui/arkui-ts/ts-basic-components-image.md) for display. Additionally, it provides APIs for obtaining and setting the color gamut and HDR metadata of images.
18
19- [Picture](#picture13): a multi-picture object composed of a main picture, auxiliary pictures, and metadata. The main picture contains the primary image information; auxiliary pictures store additional information related to the main picture; metadata stores other information related to the image. Picture provides methods for obtaining the main picture, compositing HDR images, obtaining and setting auxiliary pictures, and obtaining and setting metadata.
20
21- [AuxiliaryPicture](#auxiliarypicture13): Auxiliary pictures are used to display special information alongside the main picture, enriching the overall content of the image. The supported types of auxiliary pictures can be found in [AuxiliaryPictureType](#auxiliarypicturetype13).
22
23- [Metadata](#metadata13): used for storing image metadata. The supported metadata types can be found in [MetadataType](#metadatatype13). It includes EXIF metadata and watermark cropping metadata, both stored in Key-Value pairs. The keys for EXIF metadata can be found in [PropertyKey](#propertykey7), and the keys for watermark cropping metadata can be found in [FragmentPropertyKey](#fragmentmappropertykey13).
24
25- [ImageReceiver](#imagereceiver9): acts as a consumer of images, used for receiving and reading images from a surface.
26
27- [ImageCreator](#imagecreator9): acts as a producer of images, used for writing images into a surface.
28
29- [Image](#image9): used by ImageReceiver and ImageCreator for transferring image objects, with the actual content determined by the producer. For example, the Image object provided by a camera preview stream contains YUV data, whereas the Image object provided by a camera photo contains a JPEG file.
30
31## Modules to Import
32
33```ts
34import { image } from '@kit.ImageKit';
35```
36
37## image.createPicture<sup>13+</sup>
38
39createPicture(mainPixelmap : PixelMap): Picture
40
41Creates a Picture object based on a main PixelMap.
42
43**System capability**: SystemCapability.Multimedia.Image.Core
44
45**Parameters**
46
47| Name      | Type               | Mandatory| Description            |
48| ------------ | ------------------- | ---- | ---------------- |
49| mainPixelmap | [PixelMap](#pixelmap7) | Yes  | Main PixelMap.|
50
51**Return value**
52
53| Type              | Description             |
54| ------------------ | ----------------- |
55| [Picture](#picture13) | Picture object.|
56
57**Error codes**
58
59For details about the error codes, see [Image Error Codes](errorcode-image.md).
60
61| ID| Error Message                                                    |
62| -------- | ------------------------------------------------------------ |
63| 401      | Parameter error.Possible causes:1.Mandatory parameters are left unspecified.2.Incorrect parameter types.3.Parameter verification failed. |
64
65**Example**
66
67```ts
68import { image } from '@kit.ImageKit';
69
70async function CreatePicture(context: Context) {
71  const resourceMgr = context.resourceManager;
72  const rawFile = await resourceMgr.getRawFileContent("test.jpg");
73  let ops: image.SourceOptions = {
74    sourceDensity: 98,
75  }
76  let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
77  let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap();
78  let pictureObj: image.Picture = image.createPicture(commodityPixelMap);
79  if (pictureObj != null) {
80    console.info('Create picture succeeded');
81  } else {
82    console.error('Create picture failed');
83  }
84}
85```
86
87## image.createPictureFromParcel<sup>13+</sup>
88
89createPictureFromParcel(sequence: rpc.MessageSequence): Picture
90
91Creates a Picture object from a MessageSequence object.
92
93**System capability**: SystemCapability.Multimedia.Image.Core
94
95**Parameters**
96
97| Name  | Type                                                               | Mandatory| Description                                |
98| -------- | ------------------------------------------------------------------- | ---- | ------------------------------------ |
99| sequence | [rpc.MessageSequence](../apis-ipc-kit/js-apis-rpc.md#messagesequence9) | Yes  | MessageSequence object that stores the Picture information.|
100
101**Return value**
102
103| Type              | Description             |
104| ------------------ | ----------------- |
105| [Picture](#picture13) | Picture object.|
106
107**Error codes**
108
109For details about the error codes, see [Image Error Codes](errorcode-image.md).
110
111| ID| Error Message                                                    |
112| -------- | ------------------------------------------------------------ |
113| 401      | Parameter error.Possible causes:1.Mandatory parameters are left unspecified.2.Incorrect parameter types.3.Parameter verification failed. |
114| 62980097 |  IPC error. Possible cause: 1.IPC communication failed. 2. Image upload exception. 3. Decode process exception. 4. Insufficient memory.                                        |
115
116**Example**
117
118```ts
119import { rpc } from '@kit.IPCKit';
120import { BusinessError } from '@kit.BasicServicesKit';
121import { image } from '@kit.ImageKit';
122
123class MySequence implements rpc.Parcelable {
124  picture: image.Picture | null = null;
125  constructor(conPicture: image.Picture) {
126    this.picture = conPicture;
127  }
128  marshalling(messageSequence: rpc.MessageSequence) {
129    if(this.picture != null) {
130      this.picture.marshalling(messageSequence);
131      console.info('Marshalling success !');
132      return true;
133    } else {
134      console.error('Marshalling failed !');
135      return false;
136    }
137  }
138  unmarshalling(messageSequence : rpc.MessageSequence) {
139    this.picture = image.createPictureFromParcel(messageSequence);
140    this.picture.getMainPixelmap().getImageInfo().then((imageInfo : image.ImageInfo) => {
141      console.info('Unmarshalling to get mainPixelmap information height:' + imageInfo.size.height + ' width:' + imageInfo.size.width);
142    }).catch((error: BusinessError) => {
143      console.error('Unmarshalling failed error.code: ${error.code} ,error.message: ${error.message}');
144    });
145    return true;
146  }
147}
148
149async function Marshalling_UnMarshalling(context: Context) {
150  const resourceMgr = context.resourceManager;
151  const rawFile = await resourceMgr.getRawFileContent("test.jpg");
152  let ops: image.SourceOptions = {
153    sourceDensity: 98,
154  }
155  let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
156  let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap();
157  let pictureObj: image.Picture = image.createPicture(commodityPixelMap);
158  if (pictureObj != null) {
159    let parcelable: MySequence = new MySequence(pictureObj);
160    let data: rpc.MessageSequence = rpc.MessageSequence.create();
161    // marshalling.
162    data.writeParcelable(parcelable);
163    let ret: MySequence = new MySequence(pictureObj);
164    // unmarshalling.
165    data.readParcelable(ret);
166  } else {
167    console.error('PictureObj is null');
168  }
169}
170```
171
172## image.createPixelMap<sup>8+</sup>
173
174createPixelMap(colors: ArrayBuffer, options: InitializationOptions): Promise\<PixelMap>
175
176Creates a PixelMap object with the default BGRA_8888 format and specified pixel properties. This API uses a promise to return the result.
177
178**System capability**: SystemCapability.Multimedia.Image.Core
179
180**Parameters**
181
182| Name | Type                                            | Mandatory| Description                                                            |
183| ------- | ------------------------------------------------ | ---- | ---------------------------------------------------------------- |
184| colors  | ArrayBuffer                                      | Yes  | Buffer for storing the pixel data. It is used to initialize the pixels of the PixelMap. Before initialization, the pixel format in the buffer must be specified by [InitializationOptions](#initializationoptions8).srcPixelFormat.<br>**NOTE**: The length of the buffer required for storing the pixel data is determined by multiplying the width, height, and the number of bytes per pixel.|
185| options | [InitializationOptions](#initializationoptions8) | Yes  | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable.|
186
187**Return value**
188
189| Type                            | Description                                                                   |
190| -------------------------------- | ----------------------------------------------------------------------- |
191| Promise\<[PixelMap](#pixelmap7)> | 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.|
192
193**Example**
194
195```ts
196import { BusinessError } from '@kit.BasicServicesKit';
197
198async function CreatePixelMap() {
199  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.
200  let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
201  image.createPixelMap(color, opts).then((pixelMap: image.PixelMap) => {
202    console.info('Succeeded in creating pixelmap.');
203  }).catch((error: BusinessError) => {
204    console.error(`Failed to create pixelmap. code is ${error.code}, message is ${error.message}`);
205  })
206}
207```
208
209## image.createPixelMap<sup>8+</sup>
210
211createPixelMap(colors: ArrayBuffer, options: InitializationOptions, callback: AsyncCallback\<PixelMap>): void
212
213Creates a PixelMap object with the default BGRA_8888 format and specified pixel properties. This API uses an asynchronous callback to return the result.
214
215**System capability**: SystemCapability.Multimedia.Image.Core
216
217**Parameters**
218
219| Name  | Type                                            | Mandatory| Description                      |
220| -------- | ------------------------------------------------ | ---- | -------------------------- |
221| colors   | ArrayBuffer                                      | Yes  | Buffer for storing the pixel data. It is used to initialize the pixels of the PixelMap. Before initialization, the pixel format in the buffer must be specified by [InitializationOptions](#initializationoptions8).srcPixelFormat.<br>**NOTE**: The length of the buffer required for storing the pixel data is determined by multiplying the width, height, and the number of bytes per pixel.|
222| options  | [InitializationOptions](#initializationoptions8) | Yes  | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable.|
223| callback | AsyncCallback\<[PixelMap](#pixelmap7)>           | Yes  | Callback used to return the result. If the operation is successful, **err** is undefined and **data** is the PixelMap object obtained; otherwise, **err** is an error object.|
224
225**Example**
226
227```ts
228import { BusinessError } from '@kit.BasicServicesKit';
229
230async function CreatePixelMap() {
231  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.
232  let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
233  image.createPixelMap(color, opts, (error: BusinessError, pixelMap: image.PixelMap) => {
234    if(error) {
235      console.error(`Failed to create pixelmap. code is ${error.code}, message is ${error.message}`);
236      return;
237    } else {
238      console.info('Succeeded in creating pixelmap.');
239    }
240  })
241}
242```
243
244## image.createPixelMapUsingAllocator<sup>20+</sup>
245
246createPixelMapUsingAllocator(colors: ArrayBuffer, options: InitializationOptions, allocatorType?: AllocatorType): Promise\<PixelMap>
247
248Creates a PixelMap object with the specified properties and memory type. By default, the BGRA_8888 format is used to process data. This API uses a promise to return the result.
249
250**System capability**: SystemCapability.Multimedia.Image.Core
251
252**Parameters**
253
254| Name  | Type                                            | Mandatory| Description                      |
255| -------- | ------------------------------------------------ | ---- | -------------------------- |
256| colors   | ArrayBuffer                                      | Yes  | Buffer for storing the pixel data. It is used to initialize the pixels of the PixelMap. Before initialization, the pixel format in the buffer must be specified by [InitializationOptions](#initializationoptions8).srcPixelFormat.<br>**NOTE**: The length of the buffer required for storing the pixel data is determined by multiplying the width, height, and the number of bytes per pixel.|
257| options  | [InitializationOptions](#initializationoptions8) | Yes  | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable.|
258| allocatorType  | [AllocatorType](#allocatortype15)          | No  | Memory type of the PixelMap. The default memory type is **AllocatorType.AUTO**.<br> 1. **image.AllocatorType.AUTO**: The following formats are not supported this memory type: **UNKNOWN**, **YCBCR_P010**, **YCRCB_P010**, and **ASTC_4x4**. For RGBA_1010102, DMA memory is allocated by default. For other formats (RGB_565, RGBA_8888, BGRA_8888, and RGBAF_16), DMA memory is allocated if the dimensions exceed 512*512; otherwise, shared memory is allocated.<br>2. **image.AllocatorType.DMA**: The formats RGBA_1010102, RGB_565, RGBA_8888, BGRA_8888, and RGBAF_16 support DMA memory types. Other formats do not.<br>3. **image.AllocatorType.SHARED**: The formats UNKNOWN, RGBA_1010102, YCBCR_P010, YCRCB_P010, and ASTC_4x4 do not support shared memory. Other formats support shared memory.|
259
260**Return value**
261
262| Type                            | Description                                                                   |
263| -------------------------------- | ----------------------------------------------------------------------- |
264| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the PixelMap object.|
265
266**Error codes**
267
268For details about the error codes, see [Image Error Codes](errorcode-image.md).
269
270| ID| Error Message|
271| ------- | --------------------------------------------|
272|  7600201    | Unsupported operation. e.g.,1. The picture does not has a gainmap. 2. MainPixelMap's allocator type is not DMA. |
273|  7600301    | Memory alloc failed. |
274|  7600302    | Memory copy failed. |
275
276**Example**
277
278```ts
279import { BusinessError } from '@kit.BasicServicesKit';
280
281async function CreatePixelMapUseAllocator() {
282  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.
283  let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
284  image.createPixelMapUsingAllocator(color, opts, image.AllocatorType.AUTO).then((pixelMap: image.PixelMap) => {
285    console.info('Succeeded in creating pixelmap.');
286  }).catch((error: BusinessError) => {
287    console.error(`Failed to create pixelmap. code is ${error.code}, message is ${error.message}`);
288  })
289}
290```
291
292## image.createPixelMapFromParcel<sup>11+</sup>
293
294createPixelMapFromParcel(sequence: rpc.MessageSequence): PixelMap
295
296Creates a PixelMap object from a MessageSequence object.
297
298**System capability**: SystemCapability.Multimedia.Image.Core
299
300**Parameters**
301
302| Name                | Type                                                 | Mandatory| Description                                    |
303| ---------------------- | ----------------------------------------------------- | ---- | ---------------------------------------- |
304| sequence               | [rpc.MessageSequence](../apis-ipc-kit/js-apis-rpc.md#messagesequence9) | Yes  | MessageSequence object that stores the PixelMap information.     |
305
306**Return value**
307
308| Type                            | Description                 |
309| -------------------------------- | --------------------- |
310| [PixelMap](#pixelmap7) | PixelMap object. If the operation fails, an error is thrown.|
311
312**Error codes**
313
314For details about the error codes, see [Image Error Codes](errorcode-image.md).
315
316| ID| Error Message|
317| ------- | --------------------------------------------|
318| 62980096 | Operation failed.Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.|
319| 62980097 | IPC error. Possible cause: 1.IPC communication failed. 2. Image upload exception. 3. Decode process exception. 4. Insufficient memory.|
320| 62980115 | Invalid input parameter.|
321| 62980105 | Failed to get the data.|
322| 62980177 | Abnormal API environment.|
323| 62980178 | Failed to create the PixelMap.|
324| 62980179 | Abnormal buffer size.|
325| 62980180 | FD mapping failed. Possible cause: 1. Size and address does not match. 2. Memory map in memalloc failed.|
326| 62980246 | Failed to read the PixelMap.|
327
328**Example**
329
330```ts
331import { image } from '@kit.ImageKit';
332import { rpc } from '@kit.IPCKit';
333import { BusinessError } from '@kit.BasicServicesKit';
334
335class MySequence implements rpc.Parcelable {
336  pixel_map: image.PixelMap;
337  constructor(conPixelmap: image.PixelMap) {
338    this.pixel_map = conPixelmap;
339  }
340  marshalling(messageSequence: rpc.MessageSequence) {
341    this.pixel_map.marshalling(messageSequence);
342    return true;
343  }
344  unmarshalling(messageSequence: rpc.MessageSequence) {
345    try {
346      this.pixel_map = image.createPixelMapFromParcel(messageSequence);
347    } catch(e) {
348      let error = e as BusinessError;
349      console.error(`createPixelMapFromParcel error. code is ${error.code}, message is ${error.message}`);
350      return false;
351    }
352    return true;
353  }
354}
355async function CreatePixelMapFromParcel() {
356  const color: ArrayBuffer = new ArrayBuffer(96);
357  let bufferArr: Uint8Array = new Uint8Array(color);
358  for (let i = 0; i < bufferArr.length; i++) {
359    bufferArr[i] = 0x80;
360  }
361  let opts: image.InitializationOptions = {
362    editable: true,
363    pixelFormat: image.PixelMapFormat.BGRA_8888,
364    size: { height: 4, width: 6 },
365    alphaType: image.AlphaType.UNPREMUL
366  }
367  let pixelMap: image.PixelMap | undefined = undefined;
368  image.createPixelMap(color, opts).then((srcPixelMap: image.PixelMap) => {
369    pixelMap = srcPixelMap;
370  })
371  if (pixelMap != undefined) {
372    // Implement serialization.
373    let parcelable: MySequence = new MySequence(pixelMap);
374    let data: rpc.MessageSequence = rpc.MessageSequence.create();
375    data.writeParcelable(parcelable);
376
377    // Implement deserialization to obtain data through the RPC.
378    let ret: MySequence = new MySequence(pixelMap);
379    data.readParcelable(ret);
380
381    // Obtain the PixelMap object.
382    let unmarshPixelmap = ret.pixel_map;
383  }
384}
385```
386
387## image.createPixelMapFromSurface<sup>11+</sup>
388
389createPixelMapFromSurface(surfaceId: string, region: Region): Promise\<PixelMap>
390
391Creates a PixelMap object based on the surface ID and region information. The size of the region is specified by [Region](#region8).size. This API uses a promise to return the result.
392
393> **NOTE**
394>
395> When working with foldable devices, switching between folded and unfolded states may cause the API call to fail due to the rotation angle of surface. To address this, you need to adjust the width and height according to the rotation angle. In such cases, [image.createPixelMapFromSurface](#imagecreatepixelmapfromsurface15) is recommended.
396
397**System capability**: SystemCapability.Multimedia.Image.Core
398
399**Parameters**
400
401| Name                | Type                | Mandatory| Description                                    |
402| ---------------------- | -------------       | ---- | ---------------------------------------- |
403| surfaceId              | string              | Yes  | Surface ID, which can be obtained through the preview component, for example, [XComponent](../apis-arkui/arkui-ts/ts-basic-components-xcomponent.md).|
404| region                 | [Region](#region8)  | Yes  | Region information. The width and height in [Region](#region8).size must be the same as those of the preview stream.|
405
406**Return value**
407| Type                            | Description                 |
408| -------------------------------- | --------------------- |
409| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the PixelMap object.|
410
411**Error codes**
412
413For details about the error codes, see [Image Error Codes](errorcode-image.md).
414
415| ID| Error Message|
416| ------- | --------------------------------------------|
417| 62980115 | If the image parameter invalid.|
418| 62980105 | Failed to get the data.|
419| 62980178 | Failed to create the PixelMap.|
420
421**Example**
422
423```ts
424import { BusinessError } from '@kit.BasicServicesKit';
425
426async function CreatePixelMapFromSurface(surfaceId: string) {
427  let region: image.Region = { x: 0, y: 0, size: { height: 100, width: 100 } };
428  image.createPixelMapFromSurface(surfaceId, region).then(() => {
429    console.info('Succeeded in creating pixelmap from Surface');
430  }).catch((error: BusinessError) => {
431    console.error(`Failed to create pixelmap. code is ${error.code}, message is ${error.message}`);
432  });
433}
434```
435
436## image.createPixelMapFromSurfaceSync<sup>12+</sup>
437
438createPixelMapFromSurfaceSync(surfaceId: string, region: Region): PixelMap
439
440Creates a PixelMap object based on the surface ID and region information. This API returns the result synchronously. The size of the region is specified by [Region](#region8).size.
441
442> **NOTE**
443>
444> When working with foldable devices, switching between folded and unfolded states may cause the API call to fail due to the rotation angle of surface. To address this, you need to adjust the width and height according to the rotation angle. In such cases, [image.createPixelMapFromSurfaceSync](#imagecreatepixelmapfromsurfacesync15) is recommended.
445
446**System capability**: SystemCapability.Multimedia.Image.Core
447
448**Parameters**
449
450| Name                | Type                | Mandatory| Description                                    |
451| ---------------------- | -------------       | ---- | ---------------------------------------- |
452| surfaceId              | string              | Yes  | Surface ID, which can be obtained through the preview component, for example, [XComponent](../apis-arkui/arkui-ts/ts-basic-components-xcomponent.md).|
453| region                 | [Region](#region8)  | Yes  | Region information. The width and height in [Region](#region8).size must be the same as those of the preview stream.|
454
455**Return value**
456| Type                            | Description                 |
457| -------------------------------- | --------------------- |
458| [PixelMap](#pixelmap7) | PixelMap object. If the operation fails, an error is thrown.|
459
460**Error codes**
461
462For details about the error codes, see [Image Error Codes](errorcode-image.md).
463
464| ID| Error Message|
465| ------- | --------------------------------------------|
466|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.|
467| 62980105 | Failed to get the data.|
468| 62980178 | Failed to create the PixelMap.|
469
470**Example**
471
472```ts
473import { BusinessError } from '@kit.BasicServicesKit';
474
475async function Demo(surfaceId: string) {
476  let region: image.Region = { x: 0, y: 0, size: { height: 100, width: 100 } };
477  let pixelMap : image.PixelMap = image.createPixelMapFromSurfaceSync(surfaceId, region);
478  return pixelMap;
479}
480```
481
482## image.createPixelMapFromSurface<sup>15+</sup>
483
484createPixelMapFromSurface(surfaceId: string): Promise\<PixelMap>
485
486Creates a PixelMap object from a surface ID. This API uses a promise to return the result.
487
488**System capability**: SystemCapability.Multimedia.Image.Core
489
490**Parameters**
491
492| Name                | Type                | Mandatory| Description                                    |
493| ---------------------- | -------------       | ---- | ---------------------------------------- |
494| surfaceId              | string              | Yes  | Surface ID, which can be obtained through the preview component, for example, [XComponent](../apis-arkui/arkui-ts/ts-basic-components-xcomponent.md).|
495
496**Return value**
497| Type                            | Description                 |
498| -------------------------------- | --------------------- |
499| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the PixelMap object.|
500
501**Error codes**
502
503For details about the error codes, see [Image Error Codes](errorcode-image.md).
504
505| ID| Error Message|
506| ------- | --------------------------------------------|
507|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed|
508| 62980105 | Failed to get the data|
509| 62980178 | Failed to create the PixelMap|
510
511**Example**
512
513```ts
514import { BusinessError } from '@kit.BasicServicesKit';
515
516async function Demo(surfaceId: string) {
517  image.createPixelMapFromSurface(surfaceId).then(() => {
518    console.info('Succeeded in creating pixelmap from Surface');
519  }).catch((error: BusinessError) => {
520    console.error(`Failed to create pixelmap. code is ${error.code}, message is ${error.message}`);
521  });
522}
523```
524
525## image.createPixelMapFromSurfaceSync<sup>15+</sup>
526
527createPixelMapFromSurfaceSync(surfaceId: string): PixelMap
528
529Creates a PixelMap object from a surface ID. This API returns the result synchronously.
530
531**System capability**: SystemCapability.Multimedia.Image.Core
532
533**Parameters**
534
535| Name                | Type                | Mandatory| Description                                    |
536| ---------------------- | -------------       | ---- | ---------------------------------------- |
537| surfaceId              | string              | Yes  | Surface ID, which can be obtained through the preview component, for example, [XComponent](../apis-arkui/arkui-ts/ts-basic-components-xcomponent.md).|
538
539**Return value**
540| Type                            | Description                 |
541| -------------------------------- | --------------------- |
542| [PixelMap](#pixelmap7) | PixelMap object. If the operation fails, an error is thrown.|
543
544**Error codes**
545
546For details about the error codes, see [Image Error Codes](errorcode-image.md).
547
548| ID| Error Message|
549| ------- | --------------------------------------------|
550|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed|
551| 62980105 | Failed to get the data|
552| 62980178 | Failed to create the PixelMap|
553
554**Example**
555
556```ts
557import { BusinessError } from '@kit.BasicServicesKit';
558
559async function Demo(surfaceId: string) {
560  let pixelMap : image.PixelMap = image.createPixelMapFromSurfaceSync(surfaceId);
561  return pixelMap;
562}
563```
564## image.createPixelMapSync<sup>12+</sup>
565
566createPixelMapSync(colors: ArrayBuffer, options: InitializationOptions): PixelMap
567
568Creates a PixelMap object with the default BGRA_8888 format and specified pixel properties. This API returns the result synchronously.
569
570**System capability**: SystemCapability.Multimedia.Image.Core
571
572**Parameters**
573
574| Name | Type                                            | Mandatory| Description                                                            |
575| ------- | ------------------------------------------------ | ---- | ---------------------------------------------------------------- |
576| colors  | ArrayBuffer                                      | Yes  | Buffer for storing the pixel data. It is used to initialize the pixels of the PixelMap. Before initialization, the pixel format in the buffer must be specified by [InitializationOptions](#initializationoptions8).srcPixelFormat.<br>**NOTE**: The length of the buffer required for storing the pixel data is determined by multiplying the width, height, and the number of bytes per pixel.|
577| options | [InitializationOptions](#initializationoptions8) | Yes  | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable.|
578
579**Return value**
580| Type                            | Description                 |
581| -------------------------------- | --------------------- |
582| [PixelMap](#pixelmap7) | PixelMap object. If the operation fails, an error is thrown.|
583
584**Error codes**
585
586For details about the error codes, see [Image Error Codes](errorcode-image.md).
587
588| ID| Error Message|
589| ------- | --------------------------------------------|
590|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed|
591
592**Example**
593
594```ts
595import { BusinessError } from '@kit.BasicServicesKit';
596
597async function CreatePixelMapSync() {
598  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.
599  let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
600  let pixelMap : image.PixelMap = image.createPixelMapSync(color, opts);
601  return pixelMap;
602}
603```
604
605## image.createPixelMapSync<sup>12+</sup>
606
607createPixelMapSync(options: InitializationOptions): PixelMap
608
609Creates a PixelMap object with the specified pixel properties. This API returns the result synchronously.
610
611**System capability**: SystemCapability.Multimedia.Image.Core
612
613**Parameters**
614
615| Name | Type                                            | Mandatory| Description                                                            |
616| ------- | ------------------------------------------------ | ---- | ---------------------------------------------------------------- |
617| options | [InitializationOptions](#initializationoptions8) | Yes  | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable.|
618
619**Return value**
620| Type                            | Description                 |
621| -------------------------------- | --------------------- |
622| [PixelMap](#pixelmap7) | PixelMap object. If the operation fails, an error is thrown.|
623
624**Error codes**
625
626For details about the error codes, see [Image Error Codes](errorcode-image.md).
627
628| ID| Error Message|
629| ------- | --------------------------------------------|
630|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed|
631
632**Example**
633
634```ts
635import { BusinessError } from '@kit.BasicServicesKit';
636
637async function CreatePixelMapSync() {
638  let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
639  let pixelMap : image.PixelMap = image.createPixelMapSync(opts);
640  return pixelMap;
641}
642```
643
644## image.createPixelMapUsingAllocatorSync<sup>20+</sup>
645
646createPixelMapUsingAllocatorSync(colors: ArrayBuffer, options: InitializationOptions, allocatorType?: AllocatorType): PixelMap
647
648Creates a PixelMap object with the specified properties and memory type. By default, the BGRA_8888 format is used to process data. This API returns the result synchronously.
649
650**System capability**: SystemCapability.Multimedia.Image.Core
651
652**Parameters**
653
654| Name | Type                                            | Mandatory| Description                                                            |
655| ------- | ------------------------------------------------ | ---- | ---------------------------------------------------------------- |
656| colors  | ArrayBuffer                                      | Yes  | Buffer for storing the pixel data. It is used to initialize the pixels of the PixelMap. Before initialization, the pixel format in the buffer must be specified by [InitializationOptions](#initializationoptions8).srcPixelFormat.<br>**NOTE**: The length of the buffer required for storing the pixel data is determined by multiplying the width, height, and the number of bytes per pixel.|
657| options | [InitializationOptions](#initializationoptions8) | Yes  | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable.|
658| allocatorType  | [AllocatorType](#allocatortype15)          | No  | Memory type of the PixelMap. The default memory type is **AllocatorType.AUTO**.<br> 1. **image.AllocatorType.AUTO**: The following formats are not supported this memory type: **UNKNOWN**, **YCBCR_P010**, **YCRCB_P010**, and **ASTC_4x4**. For RGBA_1010102, DMA memory is allocated by default. For other formats (RGB_565, RGBA_8888, BGRA_8888, and RGBAF_16), DMA memory is allocated if the dimensions exceed 512*512; otherwise, shared memory is allocated.<br>2. **image.AllocatorType.DMA**: The formats RGBA_1010102, RGB_565, RGBA_8888, BGRA_8888, and RGBAF_16 support DMA memory types. Other formats do not.<br>3. **image.AllocatorType.SHARED**: The formats UNKNOWN, RGBA_1010102, YCBCR_P010, YCRCB_P010, and ASTC_4x4 do not support shared memory. Other formats support shared memory.|
659
660**Return value**
661| Type                            | Description                 |
662| -------------------------------- | --------------------- |
663| [PixelMap](#pixelmap7) | PixelMap object. If the operation fails, an error is thrown.|
664
665**Error codes**
666
667For details about the error codes, see [Image Error Codes](errorcode-image.md).
668
669| ID| Error Message|
670| ------- | --------------------------------------------|
671|  7600201    | Unsupported operation. e.g.,1. The picture does not has a gainmap. 2. MainPixelMap's allocator type is not DMA. |
672|  7600301    | Memory alloc failed. |
673|  7600302    | Memory copy failed. |
674
675**Example**
676
677```ts
678import { BusinessError } from '@kit.BasicServicesKit';
679
680async function CreatePixelMapSync() {
681  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.
682  let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
683  let pixelMap : image.PixelMap = image.createPixelMapUsingAllocatorSync(color, opts, image.AllocatorType.AUTO);
684  return pixelMap;
685}
686```
687
688## image.createPixelMapUsingAllocatorSync<sup>20+</sup>
689
690createPixelMapUsingAllocatorSync(options: InitializationOptions, allocatorType?: AllocatorType): PixelMap
691
692Creates a PixelMap object with the specified pixel properties. This API returns the result synchronously.
693
694**System capability**: SystemCapability.Multimedia.Image.Core
695
696**Parameters**
697
698| Name | Type                                            | Mandatory| Description                                                            |
699| ------- | ------------------------------------------------ | ---- | ---------------------------------------------------------------- |
700| options | [InitializationOptions](#initializationoptions8) | Yes  | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable.|
701| allocatorType  | [AllocatorType](#allocatortype15)          | No  | Memory type of the PixelMap. The default memory type is **AllocatorType.AUTO**.<br> 1. **image.AllocatorType.AUTO**: The following formats are not supported for this memory type: UNKNOWN and ASTC_4x4. For RGBA_1010102, YCBCR_P010, and YCRCB_P010, DMA memory is allocated by default. For other formats (RGB_565, RGBA_8888, BGRA_8888, and RGBAF_16), DMA memory is allocated if the dimensions exceed 512*512; otherwise, shared memory is allocated.<br>2. **image.AllocatorType.DMA**: The formats RGB_565, RGBA_8888, BGRA_8888, RGBAF_16, RGBA_1010102, YCBCR_P010, and YCRCB_P010 support DMA memory type. Other formats do not support DMA memory type.<br>3. **image.AllocatorType.SHARED**: The formats UNKNOWN, RGBA_1010102, YCBCR_P010, YCRCB_P010, and ASTC_4x4 do not support shared memory. Other formats support shared memory.|
702
703**Return value**
704| Type                            | Description                 |
705| -------------------------------- | --------------------- |
706| [PixelMap](#pixelmap7) | PixelMap object. If the operation fails, an error is thrown.|
707
708**Error codes**
709
710For details about the error codes, see [Image Error Codes](errorcode-image.md).
711
712| ID| Error Message|
713| ------- | --------------------------------------------|
714|  7600201    | Unsupported operation. e.g.,1. The picture does not has a gainmap. 2. MainPixelMap's allocator type is not DMA. |
715|  7600301    | Memory alloc failed. |
716
717**Example**
718
719```ts
720import { BusinessError } from '@kit.BasicServicesKit';
721
722async function CreatePixelMapSync() {
723  let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
724  let pixelMap : image.PixelMap = image.createPixelMapUsingAllocatorSync(opts, image.AllocatorType.AUTO);
725  return pixelMap;
726}
727```
728
729## image.createPremultipliedPixelMap<sup>12+</sup>
730
731createPremultipliedPixelMap(src: PixelMap, dst: PixelMap, callback: AsyncCallback\<void>): void
732
733Converts a non-premultiplied alpha of a PixelMap to a premultiplied one and stores the converted data to a target PixelMap. This API uses an asynchronous callback to return the result.
734
735**System capability**: SystemCapability.Multimedia.Image.Core
736
737**Parameters**
738
739| Name  | Type                                            | Mandatory| Description                      |
740| -------- | ------------------------------------------------ | ---- | -------------------------- |
741| src | [PixelMap](#pixelmap7) | Yes  | Source PixelMap object.|
742| dst | [PixelMap](#pixelmap7) | Yes  | Target PixelMap object.|
743|callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
744
745**Error codes**
746
747For details about the error codes, see [Image Error Codes](errorcode-image.md).
748
749| ID| Error Message|
750| ------- | --------------------------------------------|
751|  401          | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed|
752|  62980103     | The image data is not supported |
753|  62980246      | Failed to read the pixelMap |
754|  62980248     | Pixelmap not allow modify |
755
756**Example**
757
758```ts
759import { BusinessError } from '@kit.BasicServicesKit';
760
761async function CreatePremultipliedPixelMap() {
762  const color: ArrayBuffer = new ArrayBuffer(16); // 16 is the size of the pixel buffer to create. The value is calculated as follows: height * width * 4.
763  let bufferArr = new Uint8Array(color);
764  for (let i = 0; i < bufferArr.length; i += 4) {
765    bufferArr[i] = 255;
766    bufferArr[i+1] = 255;
767    bufferArr[i+2] = 122;
768    bufferArr[i+3] = 122;
769  }
770  let optsForUnpre: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 2, width: 2 } , alphaType: image.AlphaType.UNPREMUL}
771  let srcPixelmap = image.createPixelMapSync(color, optsForUnpre);
772  let optsForPre: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 2, width: 2 } , alphaType: image.AlphaType.PREMUL}
773  let dstPixelMap = image.createPixelMapSync(optsForPre);
774  image.createPremultipliedPixelMap(srcPixelmap, dstPixelMap, (error: BusinessError) => {
775    if(error) {
776      console.error(`Failed to convert pixelmap, error code is ${error}`);
777      return;
778    } else {
779      console.info('Succeeded in converting pixelmap.');
780    }
781  })
782}
783```
784
785## image.createPremultipliedPixelMap<sup>12+</sup>
786
787createPremultipliedPixelMap(src: PixelMap, dst: PixelMap): Promise\<void>
788
789Converts a non-premultiplied alpha of a PixelMap to a premultiplied one and stores the converted data to a target PixelMap. This API uses a promise to return the result.
790
791**System capability**: SystemCapability.Multimedia.Image.Core
792
793**Parameters**
794
795| Name  | Type                                            | Mandatory| Description                      |
796| -------- | ------------------------------------------------ | ---- | -------------------------- |
797| src | [PixelMap](#pixelmap7) | Yes  | Source PixelMap object.|
798| dst | [PixelMap](#pixelmap7) | Yes  | Target PixelMap object.|
799
800**Return value**
801
802| Type                            | Description                                                                   |
803| -------------------------------- | ----------------------------------------------------------------------- |
804| Promise\<void> | Promise that returns no value.|
805
806**Error codes**
807
808For details about the error codes, see [Image Error Codes](errorcode-image.md).
809
810| ID| Error Message|
811| ------- | --------------------------------------------|
812|  401          | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed|
813|  62980103     | The image data is not supported |
814|  62980246      | Failed to read the pixelMap |
815|  62980248     | Pixelmap not allow modify |
816
817**Example**
818
819```ts
820import { BusinessError } from '@kit.BasicServicesKit';
821
822async function CreatePremultipliedPixelMap() {
823  const color: ArrayBuffer = new ArrayBuffer(16); // 16 is the size of the pixel buffer to create. The value is calculated as follows: height * width * 4.
824  let bufferArr = new Uint8Array(color);
825  for (let i = 0; i < bufferArr.length; i += 4) {
826    bufferArr[i] = 255;
827    bufferArr[i+1] = 255;
828    bufferArr[i+2] = 122;
829    bufferArr[i+3] = 122;
830  }
831  let optsForUnpre: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 2, width: 2 } , alphaType: image.AlphaType.UNPREMUL}
832  let srcPixelmap = image.createPixelMapSync(color, optsForUnpre);
833  let optsForPre: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 2, width: 2 } , alphaType: image.AlphaType.PREMUL}
834  let dstPixelMap = image.createPixelMapSync(optsForPre);
835  image.createPremultipliedPixelMap(srcPixelmap, dstPixelMap).then(() => {
836    console.info('Succeeded in converting pixelmap.');
837  }).catch((error: BusinessError) => {
838    console.error(`Failed to convert pixelmap, error code is ${error}`);
839  })
840}
841```
842
843## image.createUnpremultipliedPixelMap<sup>12+</sup>
844
845createUnpremultipliedPixelMap(src: PixelMap, dst: PixelMap, callback: AsyncCallback\<void>): void
846
847Converts a premultiplied alpha of a PixelMap to a non-premultiplied one and stores the converted data to a target PixelMap. This API uses an asynchronous callback to return the result.
848
849**System capability**: SystemCapability.Multimedia.Image.Core
850
851**Parameters**
852
853| Name  | Type                                            | Mandatory| Description                      |
854| -------- | ------------------------------------------------ | ---- | -------------------------- |
855| src | [PixelMap](#pixelmap7) | Yes  | Source PixelMap object.|
856| dst | [PixelMap](#pixelmap7) | Yes  | Target PixelMap object.|
857|callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
858
859**Error codes**
860
861For details about the error codes, see [Image Error Codes](errorcode-image.md).
862
863| ID| Error Message|
864| ------- | --------------------------------------------|
865|  401          | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed|
866|  62980103     | The image data is not supported |
867|  62980246      | Failed to read the pixelMap |
868|  62980248     | Pixelmap not allow modify |
869
870**Example**
871
872```ts
873import { BusinessError } from '@kit.BasicServicesKit';
874
875async function CreateUnpremultipliedPixelMap() {
876  const color: ArrayBuffer = new ArrayBuffer(16); // 16 is the size of the pixel buffer to create. The value is calculated as follows: height * width * 4.
877  let bufferArr = new Uint8Array(color);
878  for (let i = 0; i < bufferArr.length; i += 4) {
879    bufferArr[i] = 255;
880    bufferArr[i+1] = 255;
881    bufferArr[i+2] = 122;
882    bufferArr[i+3] = 122;
883  }
884  let optsForPre: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 2, width: 2 } , alphaType: image.AlphaType.PREMUL}
885  let srcPixelmap = image.createPixelMapSync(color, optsForPre);
886  let optsForUnpre: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 2, width: 2 } , alphaType: image.AlphaType.UNPREMUL}
887  let dstPixelMap = image.createPixelMapSync(optsForUnpre);
888  image.createUnpremultipliedPixelMap(srcPixelmap, dstPixelMap, (error: BusinessError) => {
889    if(error) {
890      console.error(`Failed to convert pixelmap, error code is ${error}`);
891      return;
892    } else {
893      console.info('Succeeded in converting pixelmap.');
894    }
895  })
896}
897```
898
899## image.createUnpremultipliedPixelMap<sup>12+</sup>
900
901createUnpremultipliedPixelMap(src: PixelMap, dst: PixelMap): Promise\<void>
902
903Converts a premultiplied alpha of a PixelMap to a non-premultiplied one and stores the converted data to a target PixelMap. This API uses a promise to return the result.
904
905**System capability**: SystemCapability.Multimedia.Image.Core
906
907**Parameters**
908
909| Name | Type                                            | Mandatory| Description                                                            |
910| ------- | ------------------------------------------------ | ---- | ---------------------------------------------------------------- |
911| src | [PixelMap](#pixelmap7) | Yes  | Source PixelMap object.|
912| dst | [PixelMap](#pixelmap7) | Yes  | Target PixelMap object.|
913
914**Return value**
915
916| Type                            | Description                                                                   |
917| -------------------------------- | ----------------------------------------------------------------------- |
918| Promise\<void> |  Promise that returns no value.|
919
920**Error codes**
921
922For details about the error codes, see [Image Error Codes](errorcode-image.md).
923
924| ID| Error Message|
925| ------- | --------------------------------------------|
926|  401          | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.|
927|  62980103    | The image data is not supported. |
928|  62980246    | Failed to read the pixelMap. |
929|  62980248    | Pixelmap not allow modify. |
930
931**Example**
932
933```ts
934import { BusinessError } from '@kit.BasicServicesKit';
935
936async function CreateUnpremultipliedPixelMap() {
937  const color: ArrayBuffer = new ArrayBuffer(16); // 16 is the size of the pixel buffer to create. The value is calculated as follows: height * width * 4.
938  let bufferArr = new Uint8Array(color);
939  for (let i = 0; i < bufferArr.length; i += 4) {
940    bufferArr[i] = 255;
941    bufferArr[i+1] = 255;
942    bufferArr[i+2] = 122;
943    bufferArr[i+3] = 122;
944  }
945  let optsForPre: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 2, width: 2 } , alphaType: image.AlphaType.PREMUL}
946  let srcPixelmap = image.createPixelMapSync(color, optsForPre);
947  let optsForUnpre: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 2, width: 2 } , alphaType: image.AlphaType.UNPREMUL}
948  let dstPixelMap = image.createPixelMapSync(optsForUnpre);
949  image.createUnpremultipliedPixelMap(srcPixelmap, dstPixelMap).then(() => {
950    console.info('Succeeded in converting pixelmap.');
951  }).catch((error: BusinessError) => {
952    console.error(`Failed to convert pixelmap, error code is ${error}`);
953  })
954}
955```
956
957
958## Picture<sup>13+</sup>
959
960An image that contains special information can be decoded into a picture object, which generally contains the main picture, auxiliary picture, and metadata. The main picture contains most information about the image and is mainly used to render the image. The auxiliary picture is used to store data related to but different from the main picture, revealing more comprehensive details. The metadata is generally used to store information about the image file. The picture object class is used to read or write picture objects. Before calling any API in Picture, you must use [createPicture](#imagecreatepicture13) to create a Picture object.
961
962### Properties
963
964**System capability**: SystemCapability.Multimedia.Image.Core
965
966### getMainPixelmap<sup>13+</sup>
967
968getMainPixelmap(): PixelMap
969
970Obtains the PixelMap object of the main picture. This API returns the result synchronously.
971
972**System capability**: SystemCapability.Multimedia.Image.Core
973
974**Return value**
975
976| Type               | Description                  |
977| ------------------- | ---------------------- |
978| [PixelMap](#pixelmap7) | PixelMap object.|
979
980**Example**
981
982```ts
983import { BusinessError } from '@kit.BasicServicesKit';
984import { image } from '@kit.ImageKit';
985
986async function GetMainPixelmap() {
987  let funcName = "getMainPixelmap";
988  if (pictureObj != null) {
989    let mainPixelmap: image.PixelMap = pictureObj.getMainPixelmap();
990    if (mainPixelmap != null) {
991      mainPixelmap.getImageInfo().then((imageInfo: image.ImageInfo) => {
992        if (imageInfo != null) {
993          console.info('GetMainPixelmap information height:' + imageInfo.size.height + ' width:' + imageInfo.size.width);
994        }
995      }).catch((error: BusinessError) => {
996        console.error(funcName, 'Failed error.code: ${error.code} ,error.message: ${error.message}');
997      });
998    }
999  } else {
1000    console.error('PictureObj is null');
1001  }
1002}
1003```
1004
1005### getHdrComposedPixelmap<sup>13+</sup>
1006
1007getHdrComposedPixelmap(): Promise\<PixelMap>
1008
1009Generates a High Dynamic Range (HDR) image and obtains its PixelMap object. This API uses a promise to return the result.
1010
1011**System capability**: SystemCapability.Multimedia.Image.Core
1012
1013**Return value**
1014
1015| Type                         | Description                       |
1016| ----------------------------- | --------------------------- |
1017| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the PixelMap object.|
1018
1019**Error codes**
1020
1021For details about the error codes, see [Image Error Codes](errorcode-image.md).
1022
1023| ID| Error Message              |
1024| -------- | ---------------------- |
1025| 7600901  | Inner unknown error. Please check the logs for detailed information. |
1026| 7600201  | Unsupported operation. e.g.,1. The picture does not has a gainmap. 2. MainPixelMap's allocator type is not DMA. |
1027
1028**Example**
1029
1030```ts
1031import { BusinessError } from '@kit.BasicServicesKit';
1032import { image } from '@kit.ImageKit';
1033
1034async function GetHdrComposedPixelmap() {
1035  let funcName = "getHdrComposedPixelmap";
1036  if (pictureObj != null) { // An HDR image is contained.
1037    let hdrComposedPixelmap: image.PixelMap = await pictureObj.getHdrComposedPixelmap();
1038    if (hdrComposedPixelmap != null) {
1039      hdrComposedPixelmap.getImageInfo().then((imageInfo: image.ImageInfo) => {
1040        if (imageInfo != null) {
1041          console.info('GetHdrComposedPixelmap information height:' + imageInfo.size.height + ' width:' + imageInfo.size.width);
1042        }
1043      }).catch((error: BusinessError) => {
1044        console.error(funcName, 'Failed error.code: ${error.code} ,error.message: ${error.message}');
1045      });
1046    }
1047  } else {
1048    console.error('PictureObj is null');
1049  }
1050}
1051```
1052
1053### getGainmapPixelmap<sup>13+</sup>
1054
1055getGainmapPixelmap(): PixelMap | null
1056
1057Obtains the PixelMap object of the gain map.
1058
1059**System capability**: SystemCapability.Multimedia.Image.Core
1060
1061**Return value**
1062
1063| Type                     | Description                                  |
1064| ------------------------- | -------------------------------------- |
1065| [PixelMap](#pixelmap7) \| null | PixelMap object obtained. If there is no PixelMap object, null is returned.|
1066
1067**Example**
1068
1069```ts
1070import { BusinessError } from '@kit.BasicServicesKit';
1071import { image } from '@kit.ImageKit';
1072
1073async function GetGainmapPixelmap() {
1074  let funcName = "getGainmapPixelmap";
1075  if (pictureObj != null) { // A gain map is contained.
1076    let gainPixelmap: image.PixelMap | null = pictureObj.getGainmapPixelmap();
1077    if (gainPixelmap != null) {
1078      gainPixelmap.getImageInfo().then((imageInfo: image.ImageInfo) => {
1079        if (imageInfo != null) {
1080          console.info('GetGainmapPixelmap information height:' + imageInfo.size.height + ' width:' + imageInfo.size.width);
1081        } else {
1082          console.error('GainPixelmap is null');
1083        }
1084      }).catch((error: BusinessError) => {
1085        console.error(funcName, 'Failed error.code: ${error.code} ,error.message: ${error.message}');
1086      });
1087    } else {
1088      console.info('GainPixelmap is null');
1089    }
1090  } else {
1091    console.error('PictureObj is null');
1092  }
1093}
1094```
1095
1096### setAuxiliaryPicture<sup>13+</sup>
1097
1098setAuxiliaryPicture(type: AuxiliaryPictureType, auxiliaryPicture: AuxiliaryPicture): void
1099
1100Sets an auxiliary picture.
1101
1102**System capability**: SystemCapability.Multimedia.Image.Core
1103
1104**Parameters**
1105
1106| Name          | Type                | Mandatory| Description        |
1107| ---------------- | -------------------- | ---- | ------------ |
1108| type             | [AuxiliaryPictureType](#auxiliarypicturetype13) | Yes  | Type of the auxiliary picture.|
1109| auxiliaryPicture | [AuxiliaryPicture](#auxiliarypicture13)     | Yes  | AuxiliaryPicture object.|
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
1119**Example**
1120
1121```ts
1122import { image } from '@kit.ImageKit';
1123
1124async function SetAuxiliaryPicture(context: Context) {
1125  const resourceMgr = context.resourceManager;
1126  const rawFile = await resourceMgr.getRawFileContent("hdr.jpg"); // Support for HDR images is required.
1127  let ops: image.SourceOptions = {
1128    sourceDensity: 98,
1129  }
1130  let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
1131  let pixelMap: image.PixelMap = await imageSource.createPixelMap();
1132  let auxPicture: image.Picture = image.createPicture(pixelMap);
1133  if (auxPicture != null) {
1134    console.info('Create picture succeeded');
1135  } else {
1136    console.error('Create picture failed');
1137  }
1138
1139  if (pictureObj != null) {
1140    let type: image.AuxiliaryPictureType = image.AuxiliaryPictureType.GAINMAP;
1141    let auxPictureObj: image.AuxiliaryPicture | null = await auxPicture.getAuxiliaryPicture(type);
1142    if (auxPictureObj != null) {
1143      pictureObj.setAuxiliaryPicture(type, auxPictureObj);
1144    }
1145  }
1146}
1147```
1148
1149### getAuxiliaryPicture<sup>13+</sup>
1150
1151getAuxiliaryPicture(type: AuxiliaryPictureType): AuxiliaryPicture | null
1152
1153Obtains an auxiliary picture by type.
1154
1155**System capability**: SystemCapability.Multimedia.Image.Core
1156
1157**Parameters**
1158
1159| Name| Type                | Mandatory| Description        |
1160| ------ | -------------------- | ---- | ------------ |
1161| type   | [AuxiliaryPictureType](#auxiliarypicturetype13) | Yes  | Type of the auxiliary picture.|
1162
1163**Return value**
1164
1165| Type                  | Description                                          |
1166| ---------------------- | ---------------------------------------------- |
1167| [AuxiliaryPicture](#auxiliarypicture13) \| null | AuxiliaryPicture object. If there is no AuxiliaryPicture object, null is returned.|
1168
1169**Error codes**
1170
1171For details about the error codes, see [Image Error Codes](errorcode-image.md).
1172
1173| ID| Error Message                                                    |
1174| -------- | ------------------------------------------------------------ |
1175| 401      | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
1176
1177**Example**
1178
1179```ts
1180import { image } from '@kit.ImageKit';
1181
1182async function GetAuxiliaryPicture() {
1183  if (pictureObj != null) {
1184    let type: image.AuxiliaryPictureType = image.AuxiliaryPictureType.GAINMAP;
1185    let auxPictureObj: image.AuxiliaryPicture | null = pictureObj.getAuxiliaryPicture(type);
1186  }
1187}
1188```
1189
1190### setMetadata<sup>13+</sup>
1191
1192setMetadata(metadataType: MetadataType, metadata: Metadata): Promise\<void>
1193
1194Sets the metadata for this Picture object.
1195
1196**System capability**: SystemCapability.Multimedia.Image.Core
1197
1198**Parameters**
1199
1200| Name      | Type        | Mandatory| Description        |
1201| ------------ | ------------ | ---- | ------------ |
1202| metadataType | [MetadataType](#metadatatype13) | Yes  | Metadata type.|
1203| metadata     | [Metadata](#metadata13)     | Yes  | Metadata object.|
1204
1205**Return value**
1206
1207| Type          | Description                                  |
1208| -------------- | -------------------------------------- |
1209| Promise\<void> | Promise that returns no value.|
1210
1211**Error codes**
1212
1213For details about the error codes, see [Image Error Codes](errorcode-image.md).
1214
1215| ID| Error Message                                                    |
1216| -------- | ------------------------------------------------------------ |
1217| 401      | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
1218| 7600202  | Unsupported metadata. Possible causes: 1. Unsupported metadata type. 2. The metadata type does not match the auxiliary picture type. |
1219
1220**Example**
1221
1222```ts
1223import { BusinessError } from '@kit.BasicServicesKit';
1224import { image } from '@kit.ImageKit';
1225
1226async function SetPictureObjMetadata(exifContext: Context) {
1227  const exifResourceMgr = exifContext.resourceManager;
1228  const exifRawFile = await exifResourceMgr.getRawFileContent("exif.jpg"); // The image contains EXIF metadata.
1229  let exifOps: image.SourceOptions = {
1230    sourceDensity: 98,
1231  }
1232  let exifImageSource: image.ImageSource = image.createImageSource(exifRawFile.buffer as ArrayBuffer, exifOps);
1233  let exifCommodityPixelMap: image.PixelMap = await exifImageSource.createPixelMap();
1234  let exifPictureObj: image.Picture = image.createPicture(exifCommodityPixelMap);
1235  if (exifPictureObj != null) {
1236    console.info('Create picture succeeded');
1237  } else {
1238    console.error('Create picture failed');
1239  }
1240
1241  if (pictureObj != null) {
1242    let metadataType: image.MetadataType = image.MetadataType.EXIF_METADATA;
1243    let exifMetaData: image.Metadata = await exifPictureObj.getMetadata(metadataType);
1244    pictureObj.setMetadata(metadataType, exifMetaData).then(() => {
1245      console.info('Set metadata success');
1246    }).catch((error: BusinessError) => {
1247      console.error('Failed to set metadata. error.code: ' +JSON.stringify(error.code) + ' ,error.message:' + JSON.stringify(error.message));
1248    });
1249  } else {
1250    console.error('PictureObj is null');
1251  }
1252}
1253```
1254
1255### getMetadata<sup>13+</sup>
1256
1257getMetadata(metadataType: MetadataType): Promise\<Metadata>
1258
1259Obtains the metadata of this Picture object.
1260
1261**System capability**: SystemCapability.Multimedia.Image.Core
1262
1263**Parameters**
1264
1265| Name      | Type        | Mandatory| Description        |
1266| ------------ | ------------ | ---- | ------------ |
1267| metadataType | [MetadataType](#metadatatype13) | Yes  | Metadata type.|
1268
1269**Return value**
1270
1271| Type              | Description                     |
1272| ------------------ | ------------------------- |
1273| Promise\<[Metadata](#metadata13)> | Promise used to return the metadata.|
1274
1275**Error codes**
1276
1277For details about the error codes, see [Image Error Codes](errorcode-image.md).
1278
1279| ID| Error Message                                                    |
1280| -------- | ------------------------------------------------------------ |
1281| 401      | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
1282| 7600202  | Unsupported metadata. Possible causes: 1. Unsupported metadata type. 2. The metadata type does not match the auxiliary picture type. |
1283
1284**Example**
1285
1286```ts
1287import { image } from '@kit.ImageKit';
1288
1289async function GetPictureObjMetadataProperties() {
1290  if (pictureObj != null) {
1291    let metadataType: image.MetadataType = image.MetadataType.EXIF_METADATA;
1292    let pictureObjMetaData: image.Metadata = await pictureObj.getMetadata(metadataType);
1293    if (pictureObjMetaData != null) {
1294      console.info('get picture metadata success');
1295    } else {
1296      console.error('get picture metadata is failed');
1297    }
1298  } else {
1299    console.error(" pictureObj is null");
1300  }
1301}
1302```
1303
1304### marshalling<sup>13+</sup>
1305
1306marshalling(sequence: rpc.MessageSequence): void
1307
1308Marshals this Picture object and writes it to a MessageSequence object.
1309
1310**System capability**: SystemCapability.Multimedia.Image.Core
1311
1312**Parameters**
1313
1314| Name  | Type                                                               | Mandatory| Description                     |
1315| -------- | ------------------------------------------------------------------- | ---- | ------------------------- |
1316| sequence | [rpc.MessageSequence](../apis-ipc-kit/js-apis-rpc.md#messagesequence9) | Yes  | MessageSequence object.|
1317
1318**Error codes**
1319
1320For details about the error codes, see [Image Error Codes](errorcode-image.md).
1321
1322| ID| Error Message                                                    |
1323| -------- | ------------------------------------------------------------ |
1324| 401      | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
1325| 62980097 | IPC error. Possible cause: 1.IPC communication failed. 2. Image upload exception. 3. Decode process exception. 4. Insufficient memory.                                                   |
1326
1327**Example**
1328
1329```ts
1330import { BusinessError } from '@kit.BasicServicesKit';
1331import { image } from '@kit.ImageKit';
1332import { rpc } from '@kit.IPCKit';
1333
1334class MySequence implements rpc.Parcelable {
1335  picture: image.Picture | null = null;
1336  constructor(conPicture: image.Picture) {
1337    this.picture = conPicture;
1338  }
1339  marshalling(messageSequence: rpc.MessageSequence) {
1340    if(this.picture != null) {
1341      this.picture.marshalling(messageSequence);
1342      console.info('Marshalling success !');
1343      return true;
1344    } else {
1345      console.error('Marshalling failed !');
1346      return false;
1347    }
1348  }
1349  unmarshalling(messageSequence : rpc.MessageSequence) {
1350    this.picture = image.createPictureFromParcel(messageSequence);
1351    this.picture.getMainPixelmap().getImageInfo().then((imageInfo : image.ImageInfo) => {
1352      console.info('Unmarshalling to get mainPixelmap information height:' + imageInfo.size.height + ' width:' + imageInfo.size.width);
1353    }).catch((error: BusinessError) => {
1354      console.error('Unmarshalling failed error.code: ${error.code} ,error.message: ${error.message}');
1355    });
1356    return true;
1357  }
1358}
1359
1360async function Marshalling_UnMarshalling() {
1361  if (pictureObj != null) {
1362    let parcelable: MySequence = new MySequence(pictureObj);
1363    let data: rpc.MessageSequence = rpc.MessageSequence.create();
1364    // marshalling.
1365    data.writeParcelable(parcelable);
1366    let ret: MySequence = new MySequence(pictureObj);
1367    // unmarshalling.
1368    data.readParcelable(ret);
1369  } else {
1370    console.error('PictureObj is null');
1371  }
1372}
1373```
1374
1375### release<sup>13+</sup>
1376
1377release(): void
1378
1379Releases this Picture object.
1380
1381**System capability**: SystemCapability.Multimedia.Image.Core
1382
1383**Example**
1384
1385```ts
1386import { image } from '@kit.ImageKit';
1387
1388async function Release() {
1389  let funcName = "Release";
1390  if (pictureObj != null) {
1391    pictureObj.release();
1392    if (pictureObj.getMainPixelmap() == null) {
1393      console.info(funcName, 'Success !');
1394    } else {
1395      console.error(funcName, 'Failed !');
1396    }
1397  } else {
1398    console.error('PictureObj is null');
1399  }
1400}
1401```
1402
1403## PixelMap<sup>7+</sup>
1404
1405Provides APIs to read or write image data and obtain image information. Before calling any API in PixelMap, you must use [createPixelMap](#imagecreatepixelmap8) 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.
1406
1407Since API version 11, PixelMap supports cross-thread calls through workers. If a PixelMap object is invoked by another thread through [Worker](../apis-arkts/js-apis-worker.md), all APIs of the PixelMap object cannot be called in the original thread. Otherwise, error 501 is reported, indicating that the server cannot complete the request.
1408
1409Before calling any API in PixelMap, you must use [image.createPixelMap](#imagecreatepixelmap8) to create a PixelMap object.
1410
1411To develop an atomic service, use [ImageSoure](#imagesource) to create a PixelMap object.
1412
1413### Properties
1414
1415**System capability**: SystemCapability.Multimedia.Image.Core
1416
1417| Name             | Type   | Read Only| Optional| Description                      |
1418| -----------------| ------- | ---- | ---- | -------------------------- |
1419| isEditable        | boolean | Yes  | No  | Whether the PixelMap is editable. The value **true** means that the PixelMap is editable, and **false** means the opposite.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.|
1420| isStrideAlignment<sup>11+</sup> | boolean | Yes  | No  | Whether the PixelMap uses DMA memory. The value** true** means that the PixelMap uses DMA memory, and **false** means the opposite.|
1421
1422### readPixelsToBuffer<sup>7+</sup>
1423
1424readPixelsToBuffer(dst: ArrayBuffer): Promise\<void>
1425
1426Reads the pixels of this PixelMap object based on the PixelMap's pixel format and writes the data to the buffer. This API uses a promise to return the result.
1427
1428**Widget capability**: This API can be used in ArkTS widgets since API version 12.
1429
1430**Atomic service API**: This API can be used in atomic services since API version 11.
1431
1432**System capability**: SystemCapability.Multimedia.Image.Core
1433
1434**Parameters**
1435
1436| Name| Type       | Mandatory| Description                                                                                                 |
1437| ------ | ----------- | ---- | ----------------------------------------------------------------------------------------------------- |
1438| dst    | ArrayBuffer | Yes  | Buffer to which the pixels will be written. The buffer size is obtained by calling [getPixelBytesNumber](#getpixelbytesnumber7).|
1439
1440**Return value**
1441
1442| Type          | Description                                           |
1443| -------------- | ----------------------------------------------- |
1444| Promise\<void> | Promise that returns no value. |
1445
1446**Example**
1447
1448```ts
1449import { BusinessError } from '@kit.BasicServicesKit';
1450import { image } from '@kit.ImageKit';
1451
1452async function ReadPixelsToBuffer(pixelMap : image.PixelMap) {
1453  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.
1454  if (pixelMap != undefined) {
1455    pixelMap.readPixelsToBuffer(readBuffer).then(() => {
1456      console.info('Succeeded in reading image pixel data.'); // Called if the condition is met.
1457    }).catch((error: BusinessError) => {
1458      console.error(`Failed to read image pixel data. code is ${error.code}, message is ${error.message}`); // Called if no condition is met.
1459    })
1460  }
1461}
1462```
1463
1464### readPixelsToBuffer<sup>7+</sup>
1465
1466readPixelsToBuffer(dst: ArrayBuffer, callback: AsyncCallback\<void>): void
1467
1468Reads the pixels of this PixelMap object based on the PixelMap's pixel format and writes the data to the buffer. This API uses an asynchronous callback to return the result.
1469
1470**Widget capability**: This API can be used in ArkTS widgets since API version 12.
1471
1472**Atomic service API**: This API can be used in atomic services since API version 11.
1473
1474**System capability**: SystemCapability.Multimedia.Image.Core
1475
1476**Parameters**
1477
1478| Name  | Type                | Mandatory| Description                                                                                                 |
1479| -------- | -------------------- | ---- | ----------------------------------------------------------------------------------------------------- |
1480| dst      | ArrayBuffer          | Yes  | Buffer to which the pixels will be written. The buffer size is obtained by calling [getPixelBytesNumber](#getpixelbytesnumber7).|
1481| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. |
1482
1483**Example**
1484
1485```ts
1486import { BusinessError } from '@kit.BasicServicesKit';
1487import { image } from '@kit.ImageKit';
1488
1489async function ReadPixelsToBuffer(pixelMap : image.PixelMap) {
1490  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.
1491  if (pixelMap != undefined) {
1492    pixelMap.readPixelsToBuffer(readBuffer, (error: BusinessError, res: void) => {
1493      if(error) {
1494        console.error(`Failed to read image pixel data. code is ${error.code}, message is ${error.message}`); // Called if no condition is met.
1495        return;
1496      } else {
1497        console.info('Succeeded in reading image pixel data.');  // Called if the condition is met.
1498      }
1499    })
1500  }
1501}
1502```
1503
1504### readPixelsToBufferSync<sup>12+</sup>
1505
1506readPixelsToBufferSync(dst: ArrayBuffer): void
1507
1508Reads the pixels of this PixelMap object based on the PixelMap's pixel format and writes the data to the buffer. This API returns the result synchronously.
1509
1510**Widget capability**: This API can be used in ArkTS widgets since API version 12.
1511
1512**Atomic service API**: This API can be used in atomic services since API version 12.
1513
1514**System capability**: SystemCapability.Multimedia.Image.Core
1515
1516**Parameters**
1517
1518| Name  | Type                | Mandatory| Description                                                                                                 |
1519| -------- | -------------------- | ---- | ----------------------------------------------------------------------------------------------------- |
1520| dst      | ArrayBuffer          | Yes  | Buffer to which the pixels will be written. The buffer size is obtained by calling [getPixelBytesNumber](#getpixelbytesnumber7).|
1521
1522**Error codes**
1523
1524For details about the error codes, see [Image Error Codes](errorcode-image.md).
1525
1526| ID| Error Message|
1527| ------- | --------------------------------------------|
1528|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
1529|  501    | Resource Unavailable |
1530
1531**Example**
1532
1533```ts
1534import { BusinessError } from '@kit.BasicServicesKit';
1535import { image } from '@kit.ImageKit';
1536
1537async function ReadPixelsToBufferSync(pixelMap : image.PixelMap) {
1538  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.
1539  if (pixelMap != undefined) {
1540    pixelMap.readPixelsToBufferSync(readBuffer);
1541  }
1542}
1543```
1544
1545### readPixels<sup>7+</sup>
1546
1547readPixels(area: PositionArea): Promise\<void>
1548
1549Reads the pixels in the area specified by [PositionArea](#positionarea7).region of this PixelMap object in the BGRA_8888 format and writes the data to the [PositionArea](#positionarea7).pixels buffer. This API uses a promise to return the result.
1550
1551You can use a formula to calculate the size of the memory to be applied for based on **PositionArea**.
1552
1553YUV region calculation formula: region to read (region.size{width * height}) * 1.5 (1 * Y component + 0.25 * U component + 0.25 * V component)
1554
1555RGBA region calculation formula: region to read (region.size{width * height}) * 4 (1 * R component + 1 * G component + 1 * B component + 1 * A component)
1556
1557**Widget capability**: This API can be used in ArkTS widgets since API version 12.
1558
1559**Atomic service API**: This API can be used in atomic services since API version 11.
1560
1561**System capability**: SystemCapability.Multimedia.Image.Core
1562
1563**Parameters**
1564
1565| Name| Type                          | Mandatory| Description                    |
1566| ------ | ------------------------------ | ---- | ------------------------ |
1567| area   | [PositionArea](#positionarea7) | Yes  | Area from which the pixels will be read.|
1568
1569**Return value**
1570
1571| Type          | Description                                               |
1572| :------------- | :-------------------------------------------------- |
1573| Promise\<void> | Promise that returns no value. |
1574
1575**Example**
1576
1577```ts
1578import { BusinessError } from '@kit.BasicServicesKit';
1579import { image } from '@kit.ImageKit';
1580
1581async function ReadPixelsRGBA(pixelMap : image.PixelMap) {
1582  const area: image.PositionArea = {
1583    pixels: new ArrayBuffer(8), // 8 is the size of the PixelMap buffer to create. The value is calculated as follows: height * width * 4.
1584    offset: 0,
1585    stride: 8,
1586    region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
1587  };
1588  if (pixelMap != undefined) {
1589    pixelMap.readPixels(area).then(() => {
1590      console.info('Succeeded in reading the image data in the area.'); // Called if the condition is met.
1591    }).catch((error: BusinessError) => {
1592      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.
1593    })
1594  }
1595}
1596
1597async function ReadPixelsYUV(pixelMap : image.PixelMap) {
1598  const area: image.PositionArea = {
1599    pixels: new ArrayBuffer(6),  // 6 is the size of the PixelMap buffer to create. The value is calculated as follows: height * width * 1.5.
1600    offset: 0,
1601    stride: 8,
1602    region: { size: { height: 2, width: 2 }, x: 0, y: 0 }
1603  };
1604  if (pixelMap != undefined) {
1605    pixelMap.readPixels(area).then(() => {
1606      console.info('Succeeded in reading the image data in the area.'); // Called if the condition is met.
1607    }).catch((error: BusinessError) => {
1608      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.
1609    })
1610  }
1611}
1612```
1613
1614### readPixels<sup>7+</sup>
1615
1616readPixels(area: PositionArea, callback: AsyncCallback\<void>): void
1617
1618Reads the pixels in the area specified by [PositionArea](#positionarea7).region of this PixelMap object in the BGRA_8888 format and writes the data to the [PositionArea](#positionarea7).pixels buffer. This API uses an asynchronous callback to return the result.
1619
1620You can use a formula to calculate the size of the memory to be applied for based on **PositionArea**.
1621
1622YUV region calculation formula: region to read (region.size{width * height}) * 1.5 (1 * Y component + 0.25 * U component + 0.25 * V component)
1623
1624RGBA region calculation formula: region to read (region.size{width * height}) * 4 (1 * R component + 1 * G component + 1 * B component + 1 * A component)
1625
1626**Widget capability**: This API can be used in ArkTS widgets since API version 12.
1627
1628**Atomic service API**: This API can be used in atomic services since API version 11.
1629
1630**System capability**: SystemCapability.Multimedia.Image.Core
1631
1632**Parameters**
1633
1634| Name  | Type                          | Mandatory| Description                          |
1635| -------- | ------------------------------ | ---- | ------------------------------ |
1636| area     | [PositionArea](#positionarea7) | Yes  | Area from which the pixels will be read.      |
1637| callback | AsyncCallback\<void>           | Yes  |  Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
1638
1639**Example**
1640
1641```ts
1642import { BusinessError } from '@kit.BasicServicesKit';
1643import { image } from '@kit.ImageKit';
1644
1645async function ReadPixelsRGBA(pixelMap : image.PixelMap) {
1646  const area: image.PositionArea = {
1647    pixels: new ArrayBuffer(8), // 8 is the size of the PixelMap buffer to create. The value is calculated as follows: height * width * 4.
1648    offset: 0,
1649    stride: 8,
1650    region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
1651  };
1652  if (pixelMap != undefined) {
1653    pixelMap.readPixels(area, (error: BusinessError) => {
1654      if (error) {
1655        console.error(`Failed to read pixelmap from the specified area. code is ${error.code}, message is ${error.message}`);
1656        return;
1657      } else {
1658        console.info('Succeeded in reading pixelmap from the specified area.');
1659      }
1660    })
1661  }
1662}
1663
1664async function ReadPixelsYUV(pixelMap : image.PixelMap) {
1665  const area: image.PositionArea = {
1666    pixels: new ArrayBuffer(6),  // 6 is the size of the PixelMap buffer to create. The value is calculated as follows: height * width * 1.5.
1667    offset: 0,
1668    stride: 8,
1669    region: { size: { height: 2, width: 2 }, x: 0, y: 0 }
1670  };
1671  if (pixelMap != undefined) {
1672    pixelMap.readPixels(area, (error: BusinessError) => {
1673      if (error) {
1674        console.error(`Failed to read pixelmap from the specified area. code is ${error.code}, message is ${error.message}`);
1675        return;
1676      } else {
1677        console.info('Succeeded in reading pixelmap from the specified area.');
1678      }
1679    })
1680  }
1681}
1682```
1683
1684### readPixelsSync<sup>12+</sup>
1685
1686readPixelsSync(area: PositionArea): void
1687
1688Reads the pixels in the area specified by [PositionArea](#positionarea7).region of this PixelMap object in the BGRA_8888 format and writes the data to the [PositionArea](#positionarea7).pixels buffer. This API returns the result synchronously.
1689
1690**Atomic service API**: This API can be used in atomic services since API version 12.
1691
1692**System capability**: SystemCapability.Multimedia.Image.Core
1693
1694**Parameters**
1695
1696| Name| Type                          | Mandatory| Description                    |
1697| ------ | ------------------------------ | ---- | ------------------------ |
1698| area   | [PositionArea](#positionarea7) | Yes  | Area from which the pixels will be read.|
1699
1700**Error codes**
1701
1702For details about the error codes, see [Image Error Codes](errorcode-image.md).
1703
1704| ID| Error Message|
1705| ------- | --------------------------------------------|
1706|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
1707|  501    | Resource Unavailable |
1708
1709**Example**
1710
1711```ts
1712import { BusinessError } from '@kit.BasicServicesKit';
1713
1714async function ReadPixelsSync(pixelMap : image.PixelMap) {
1715  const area : image.PositionArea = {
1716    pixels: new ArrayBuffer(8),
1717    offset: 0,
1718    stride: 8,
1719    region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
1720  };
1721  if (pixelMap != undefined) {
1722    pixelMap.readPixelsSync(area);
1723  }
1724}
1725```
1726
1727### writePixels<sup>7+</sup>
1728
1729writePixels(area: PositionArea): Promise\<void>
1730
1731Reads the pixels in the [PositionArea](#positionarea7).pixels buffer in the BGRA_8888 format and writes the data to the area specified by [PositionArea](#positionarea7).region in this PixelMap object. This API uses a promise to return the result.
1732
1733You can use a formula to calculate the size of the memory to be applied for based on **PositionArea**.
1734
1735YUV region calculation formula: region to read (region.size{width * height}) * 1.5 (1 * Y component + 0.25 * U component + 0.25 * V component)
1736
1737RGBA region calculation formula: region to read (region.size{width * height}) * 4 (1 * R component + 1 * G component + 1 * B component + 1 * A component)
1738
1739**Widget capability**: This API can be used in ArkTS widgets since API version 12.
1740
1741**Atomic service API**: This API can be used in atomic services since API version 11.
1742
1743**System capability**: SystemCapability.Multimedia.Image.Core
1744
1745**Parameters**
1746
1747| Name| Type                          | Mandatory| Description                |
1748| ------ | ------------------------------ | ---- | -------------------- |
1749| area   | [PositionArea](#positionarea7) | Yes  | Area to which the pixels will be written.|
1750
1751**Return value**
1752
1753| Type          | Description                                               |
1754| :------------- | :-------------------------------------------------- |
1755| Promise\<void> | Promise that returns no value. |
1756
1757**Example**
1758
1759```ts
1760import { BusinessError } from '@kit.BasicServicesKit';
1761
1762async function WritePixelsRGBA() {
1763  const area: image.PositionArea = {
1764    pixels: new ArrayBuffer(8), // 8 is the size of the PixelMap buffer to create. The value is calculated as follows: height * width * 4.
1765    offset: 0,
1766    stride: 8,
1767    region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
1768  };
1769  let bufferArr: Uint8Array = new Uint8Array(area.pixels);
1770  for (let i = 0; i < bufferArr.length; i++) {
1771    bufferArr[i] = i + 1;
1772  }
1773  if (pixelMap != undefined) {
1774    pixelMap.writePixels(area).then(() => {
1775      console.info('Succeeded in writing pixelmap into the specified area.');
1776    }).catch((error: BusinessError) => {
1777      console.error(`Failed to write pixelmap into the specified area. code is ${error.code}, message is ${error.message}`);
1778    })
1779  }
1780}
1781
1782async function WritePixelsYUV() {
1783  const area: image.PositionArea = {
1784    pixels: new ArrayBuffer(6),  // 6 is the size of the PixelMap buffer to create. The value is calculated as follows: height * width * 1.5.
1785    offset: 0,
1786    stride: 8,
1787    region: { size: { height: 2, width: 2 }, x: 0, y: 0 }
1788  };
1789  let bufferArr: Uint8Array = new Uint8Array(area.pixels);
1790  for (let i = 0; i < bufferArr.length; i++) {
1791    bufferArr[i] = i + 1;
1792  }
1793  if (pixelMap != undefined) {
1794    pixelMap.writePixels(area).then(() => {
1795      console.info('Succeeded in writing pixelmap into the specified area.');
1796    }).catch((error: BusinessError) => {
1797      console.error(`Failed to write pixelmap into the specified area. code is ${error.code}, message is ${error.message}`);
1798    })
1799  }
1800}
1801```
1802
1803### writePixels<sup>7+</sup>
1804
1805writePixels(area: PositionArea, callback: AsyncCallback\<void>): void
1806
1807Reads the pixels in the [PositionArea](#positionarea7).pixels buffer in the BGRA_8888 format and writes the data to the area specified by [PositionArea](#positionarea7).region in this PixelMap object. This API uses an asynchronous callback to return the result.
1808
1809You can use a formula to calculate the size of the memory to be applied for based on **PositionArea**.
1810
1811YUV region calculation formula: region to read (region.size{width * height}) * 1.5 (1 * Y component + 0.25 * U component + 0.25 * V component)
1812
1813RGBA region calculation formula: region to read (region.size{width * height}) * 4 (1 * R component + 1 * G component + 1 * B component + 1 * A component)
1814
1815**Widget capability**: This API can be used in ArkTS widgets since API version 12.
1816
1817**Atomic service API**: This API can be used in atomic services since API version 11.
1818
1819**System capability**: SystemCapability.Multimedia.Image.Core
1820
1821**Parameters**
1822
1823| Name   | Type                          | Mandatory| Description                          |
1824| --------- | ------------------------------ | ---- | ------------------------------ |
1825| area      | [PositionArea](#positionarea7) | Yes  | Area to which the pixels will be written.          |
1826| callback  | AsyncCallback\<void>           | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
1827
1828**Example**
1829
1830```ts
1831import { BusinessError } from '@kit.BasicServicesKit';
1832
1833async function WritePixelsRGBA() {
1834  const area: image.PositionArea = { pixels: new ArrayBuffer(8), // 8 is the size of the PixelMap buffer to create. The value is calculated as follows: height * width * 4.
1835    offset: 0,
1836    stride: 8,
1837    region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
1838  };
1839  let bufferArr: Uint8Array = new Uint8Array(area.pixels);
1840  for (let i = 0; i < bufferArr.length; i++) {
1841    bufferArr[i] = i + 1;
1842  }
1843  if (pixelMap != undefined) {
1844    pixelMap.writePixels(area, (error : BusinessError) => {
1845      if (error) {
1846        console.error(`Failed to write pixelmap into the specified area. code is ${error.code}, message is ${error.message}`);
1847        return;
1848      } else {
1849        console.info('Succeeded in writing pixelmap into the specified area.');
1850      }
1851    })
1852  }
1853}
1854
1855async function WritePixelsYUV() {
1856  const area: image.PositionArea = { pixels: new ArrayBuffer(6), // 6 is the size of the PixelMap buffer to create. The value is calculated as follows: height * width * 1.5.
1857    offset: 0,
1858    stride: 8,
1859    region: { size: { height: 2, width: 2 }, x: 0, y: 0 }
1860  };
1861  let bufferArr: Uint8Array = new Uint8Array(area.pixels);
1862  for (let i = 0; i < bufferArr.length; i++) {
1863    bufferArr[i] = i + 1;
1864  }
1865  if (pixelMap != undefined) {
1866    pixelMap.writePixels(area, (error : BusinessError) => {
1867      if (error) {
1868        console.error(`Failed to write pixelmap into the specified area. code is ${error.code}, message is ${error.message}`);
1869        return;
1870      } else {
1871        console.info('Succeeded in writing pixelmap into the specified area.');
1872      }
1873    })
1874  }
1875}
1876```
1877
1878### writePixelsSync<sup>12+</sup>
1879
1880writePixelsSync(area: PositionArea): void
1881
1882Reads the pixels in the [PositionArea](#positionarea7).pixels buffer in the BGRA_8888 format and writes the data to the area specified by [PositionArea](#positionarea7).region in this PixelMap object. This API returns the result synchronously.
1883
1884**Widget capability**: This API can be used in ArkTS widgets since API version 12.
1885
1886**Atomic service API**: This API can be used in atomic services since API version 12.
1887
1888**System capability**: SystemCapability.Multimedia.Image.Core
1889
1890**Parameters**
1891
1892| Name| Type                          | Mandatory| Description                |
1893| ------ | ------------------------------ | ---- | -------------------- |
1894| area   | [PositionArea](#positionarea7) | Yes  | Area to which the pixels will be written.|
1895
1896**Error codes**
1897
1898For details about the error codes, see [Image Error Codes](errorcode-image.md).
1899
1900| ID| Error Message|
1901| ------- | --------------------------------------------|
1902|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
1903|  501    | Resource Unavailable |
1904
1905**Example**
1906
1907```ts
1908import { BusinessError } from '@kit.BasicServicesKit';
1909
1910async function WritePixelsSync() {
1911  const area: image.PositionArea = {
1912    pixels: new ArrayBuffer(8),
1913    offset: 0,
1914    stride: 8,
1915    region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
1916  };
1917  let bufferArr: Uint8Array = new Uint8Array(area.pixels);
1918  for (let i = 0; i < bufferArr.length; i++) {
1919    bufferArr[i] = i + 1;
1920  }
1921  if (pixelMap != undefined) {
1922    pixelMap.writePixelsSync(area);
1923  }
1924}
1925```
1926
1927### writeBufferToPixels<sup>7+</sup>
1928
1929writeBufferToPixels(src: ArrayBuffer): Promise\<void>
1930
1931Reads the pixels in the buffer based on the PixelMap's pixel format and writes the data to this PixelMap object. This API uses a promise to return the result.
1932
1933**Widget capability**: This API can be used in ArkTS widgets since API version 12.
1934
1935**Atomic service API**: This API can be used in atomic services since API version 11.
1936
1937**System capability**: SystemCapability.Multimedia.Image.Core
1938
1939**Parameters**
1940
1941| Name| Type       | Mandatory| Description          |
1942| ------ | ----------- | ---- | -------------- |
1943| src    | ArrayBuffer | Yes  | Buffer from which the pixels are read. The buffer size is obtained by calling [getPixelBytesNumber](#getpixelbytesnumber7).|
1944
1945**Return value**
1946
1947| Type          | Description                                           |
1948| -------------- | ----------------------------------------------- |
1949| Promise\<void> | Promise that returns no value. |
1950
1951**Example**
1952
1953```ts
1954import { BusinessError } from '@kit.BasicServicesKit';
1955
1956async function WriteBufferToPixels() {
1957  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.
1958  let bufferArr: Uint8Array = new Uint8Array(color);
1959  for (let i = 0; i < bufferArr.length; i++) {
1960    bufferArr[i] = i + 1;
1961  }
1962  if (pixelMap != undefined) {
1963    pixelMap.writeBufferToPixels(color).then(() => {
1964      console.info("Succeeded in writing data from a buffer to a PixelMap.");
1965    }).catch((error: BusinessError) => {
1966      console.error(`Failed to write data from a buffer to a PixelMap. code is ${error.code}, message is ${error.message}`);
1967    })
1968  }
1969}
1970```
1971
1972### writeBufferToPixels<sup>7+</sup>
1973
1974writeBufferToPixels(src: ArrayBuffer, callback: AsyncCallback\<void>): void
1975
1976Reads the pixels in the buffer based on the PixelMap's pixel format and writes the data to this PixelMap object. This API uses an asynchronous callback to return the result.
1977
1978**Widget capability**: This API can be used in ArkTS widgets since API version 12.
1979
1980**Atomic service API**: This API can be used in atomic services since API version 11.
1981
1982**System capability**: SystemCapability.Multimedia.Image.Core
1983
1984**Parameters**
1985
1986| Name  | Type                | Mandatory| Description                          |
1987| -------- | -------------------- | ---- | ------------------------------ |
1988| src      | ArrayBuffer          | Yes  | Buffer from which the pixels are read. The buffer size is obtained by calling [getPixelBytesNumber](#getpixelbytesnumber7).|
1989| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the pixels in the buffer are successfully written to the PixelMap, **err** is **undefined**; otherwise, **err** is an error object.|
1990
1991**Example**
1992
1993```ts
1994import { BusinessError } from '@kit.BasicServicesKit';
1995
1996async function WriteBufferToPixels() {
1997  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.
1998  let bufferArr: Uint8Array = new Uint8Array(color);
1999  for (let i = 0; i < bufferArr.length; i++) {
2000    bufferArr[i] = i + 1;
2001  }
2002  if (pixelMap != undefined) {
2003    pixelMap.writeBufferToPixels(color, (error: BusinessError) => {
2004      if (error) {
2005        console.error(`Failed to write data from a buffer to a PixelMap. code is ${error.code}, message is ${error.message}`);
2006        return;
2007      } else {
2008        console.info("Succeeded in writing data from a buffer to a PixelMap.");
2009      }
2010    })
2011  }
2012}
2013```
2014
2015### writeBufferToPixelsSync<sup>12+</sup>
2016
2017writeBufferToPixelsSync(src: ArrayBuffer): void
2018
2019Reads the pixels in the buffer based on the PixelMap's pixel format and writes the data to this PixelMap object. This API returns the result synchronously.
2020
2021**Atomic service API**: This API can be used in atomic services since API version 12.
2022
2023**System capability**: SystemCapability.Multimedia.Image.Core
2024
2025**Parameters**
2026
2027| Name| Type       | Mandatory| Description          |
2028| ------ | ----------- | ---- | -------------- |
2029| src    | ArrayBuffer | Yes  | Buffer from which the pixels are read. The buffer size is obtained by calling [getPixelBytesNumber](#getpixelbytesnumber7).|
2030
2031**Error codes**
2032
2033For details about the error codes, see [Image Error Codes](errorcode-image.md).
2034
2035| ID| Error Message|
2036| ------- | --------------------------------------------|
2037|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
2038|  501    | Resource Unavailable |
2039
2040**Example**
2041
2042```ts
2043import { BusinessError } from '@kit.BasicServicesKit';
2044
2045async function WriteBufferToPixelsSync() {
2046  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.
2047  let bufferArr : Uint8Array = new Uint8Array(color);
2048  for (let i = 0; i < bufferArr.length; i++) {
2049    bufferArr[i] = i + 1;
2050  }
2051  if (pixelMap != undefined) {
2052    pixelMap.writeBufferToPixelsSync(color);
2053  }
2054}
2055```
2056
2057
2058### getImageInfo<sup>7+</sup>
2059
2060getImageInfo(): Promise\<ImageInfo>
2061
2062Obtains the image information. This API uses a promise to return the result.
2063
2064**Widget capability**: This API can be used in ArkTS widgets since API version 12.
2065
2066**Atomic service API**: This API can be used in atomic services since API version 11.
2067
2068**System capability**: SystemCapability.Multimedia.Image.Core
2069
2070**Return value**
2071
2072| Type                             | Description                                                       |
2073| --------------------------------- | ----------------------------------------------------------- |
2074| Promise\<[ImageInfo](#imageinfo)> | Promise used to return the image information.|
2075
2076**Example**
2077
2078```ts
2079import { BusinessError } from '@kit.BasicServicesKit';
2080
2081async function GetImageInfo() {
2082  if (pixelMap != undefined) {
2083    pixelMap.getImageInfo().then((imageInfo: image.ImageInfo) => {
2084      if (imageInfo != undefined) {
2085        console.info("Succeeded in obtaining the image pixel map information."+ imageInfo.size.height);
2086      }
2087    }).catch((error: BusinessError) => {
2088      console.error(`Failed to obtain the image pixel map information. code is ${error.code}, message is ${error.message}`);
2089    })
2090  }
2091}
2092```
2093
2094### getImageInfo<sup>7+</sup>
2095
2096getImageInfo(callback: AsyncCallback\<ImageInfo>): void
2097
2098Obtains the image information. This API uses an asynchronous callback to return the result.
2099
2100**Widget capability**: This API can be used in ArkTS widgets since API version 12.
2101
2102**Atomic service API**: This API can be used in atomic services since API version 11.
2103
2104**System capability**: SystemCapability.Multimedia.Image.Core
2105
2106**Parameters**
2107
2108| Name  | Type                                   | Mandatory| Description                                                        |
2109| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
2110| callback | AsyncCallback\<[ImageInfo](#imageinfo)> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the image information obtained; otherwise, **err** is an error object.|
2111
2112**Example**
2113
2114```ts
2115import { BusinessError } from '@kit.BasicServicesKit';
2116
2117async function GetImageInfo() {
2118  if (pixelMap != undefined) {
2119    pixelMap.getImageInfo((error: BusinessError, imageInfo: image.ImageInfo) => {
2120      if (error) {
2121        console.error(`Failed to obtain the image pixel map information. code is ${error.code}, message is ${error.message}`);
2122        return;
2123      } else {
2124        console.info("Succeeded in obtaining the image pixel map information."+ imageInfo.size.height);
2125      }
2126    })
2127  }
2128}
2129```
2130
2131### getImageInfoSync<sup>12+</sup>
2132
2133getImageInfoSync(): ImageInfo
2134
2135Obtains the image information. This API returns the result synchronously.
2136
2137**Widget capability**: This API can be used in ArkTS widgets since API version 12.
2138
2139**Atomic service API**: This API can be used in atomic services since API version 12.
2140
2141**System capability**: SystemCapability.Multimedia.Image.ImageSource
2142
2143**Return value**
2144
2145| Type                             | Description                                                       |
2146| --------------------------------- | ----------------------------------------------------------- |
2147| [ImageInfo](#imageinfo)           | Image information.                                               |
2148
2149**Error codes**
2150
2151For details about the error codes, see [Image Error Codes](errorcode-image.md).
2152
2153| ID| Error Message|
2154| ------- | --------------------------------------------|
2155|  501    | Resource Unavailable |
2156
2157**Example**
2158
2159```ts
2160import { BusinessError } from '@kit.BasicServicesKit';
2161
2162async function GetImageInfoSync() {
2163  if (pixelMap != undefined) {
2164    let imageInfo : image.ImageInfo = pixelMap.getImageInfoSync();
2165    return imageInfo;
2166  }
2167  return undefined;
2168}
2169```
2170
2171### getBytesNumberPerRow<sup>7+</sup>
2172
2173getBytesNumberPerRow(): number
2174
2175Obtains the number of bytes per row of this image.
2176
2177**Widget capability**: This API can be used in ArkTS widgets since API version 12.
2178
2179**Atomic service API**: This API can be used in atomic services since API version 11.
2180
2181**System capability**: SystemCapability.Multimedia.Image.Core
2182
2183**Return value**
2184
2185| Type  | Description                |
2186| ------ | -------------------- |
2187| number | Number of bytes per row.|
2188
2189**Example**
2190
2191```ts
2192let rowCount: number = pixelMap.getBytesNumberPerRow();
2193```
2194
2195### getPixelBytesNumber<sup>7+</sup>
2196
2197getPixelBytesNumber(): number
2198
2199Obtains the total number of bytes of this image.
2200
2201**Widget capability**: This API can be used in ArkTS widgets since API version 12.
2202
2203**Atomic service API**: This API can be used in atomic services since API version 11.
2204
2205**System capability**: SystemCapability.Multimedia.Image.Core
2206
2207**Return value**
2208
2209| Type  | Description                |
2210| ------ | -------------------- |
2211| number | Total number of bytes.|
2212
2213**Example**
2214
2215```ts
2216let pixelBytesNumber: number = pixelMap.getPixelBytesNumber();
2217```
2218
2219### getDensity<sup>9+</sup>
2220
2221getDensity():number
2222
2223Obtains the pixel density of this image.
2224
2225**Widget capability**: This API can be used in ArkTS widgets since API version 12.
2226
2227**Atomic service API**: This API can be used in atomic services since API version 11.
2228
2229**System capability**: SystemCapability.Multimedia.Image.Core
2230
2231**Return value**
2232
2233| Type  | Description           |
2234| ------ | --------------- |
2235| number | Pixel density, in ppi.|
2236
2237**Example**
2238
2239```ts
2240let getDensity: number = pixelMap.getDensity();
2241```
2242
2243### opacity<sup>9+</sup>
2244
2245opacity(rate: number, callback: AsyncCallback\<void>): void
2246
2247Sets an opacity rate for this image. This API uses an asynchronous callback to return the result. It is invalid for YUV images.
2248
2249**Widget capability**: This API can be used in ArkTS widgets since API version 12.
2250
2251**Atomic service API**: This API can be used in atomic services since API version 11.
2252
2253**System capability**: SystemCapability.Multimedia.Image.Core
2254
2255**Parameters**
2256
2257| Name  | Type                | Mandatory| Description                          |
2258| -------- | -------------------- | ---- | ------------------------------ |
2259| rate     | number               | Yes  | Opacity rate. The value range is (0,1]. |
2260| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
2261
2262**Example**
2263
2264```ts
2265import { BusinessError } from '@kit.BasicServicesKit';
2266
2267async function Opacity() {
2268  let rate: number = 0.5;
2269  if (pixelMap != undefined) {
2270    pixelMap.opacity(rate, (err: BusinessError) => {
2271      if (err) {
2272        console.error(`Failed to set opacity. code is ${err.code}, message is ${err.message}`);
2273        return;
2274      } else {
2275        console.info("Succeeded in setting opacity.");
2276      }
2277    })
2278  }
2279}
2280```
2281
2282### opacity<sup>9+</sup>
2283
2284opacity(rate: number): Promise\<void>
2285
2286Sets an opacity rate for this image. This API uses a promise to return the result. It is invalid for YUV images.
2287
2288**Widget capability**: This API can be used in ArkTS widgets since API version 12.
2289
2290**Atomic service API**: This API can be used in atomic services since API version 11.
2291
2292**System capability**: SystemCapability.Multimedia.Image.Core
2293
2294**Parameters**
2295
2296| Name| Type  | Mandatory| Description                       |
2297| ------ | ------ | ---- | --------------------------- |
2298| rate   | number | Yes  | Opacity rate. The value range is (0,1].|
2299
2300**Return value**
2301
2302| Type          | Description                                           |
2303| -------------- | ----------------------------------------------- |
2304| Promise\<void> | Promise that returns no value. |
2305
2306**Example**
2307
2308```ts
2309import { BusinessError } from '@kit.BasicServicesKit';
2310
2311async function Opacity() {
2312  let rate: number = 0.5;
2313  if (pixelMap != undefined) {
2314    pixelMap.opacity(rate).then(() => {
2315      console.info('Succeeded in setting opacity.');
2316    }).catch((err: BusinessError) => {
2317      console.error(`Failed to set opacity. code is ${err.code}, message is ${err.message}`);
2318    })
2319  }
2320}
2321```
2322
2323### opacitySync<sup>12+</sup>
2324
2325opacitySync(rate: number): void
2326
2327Sets an opacity rate for this image. This API returns the result synchronously. It is invalid for YUV images.
2328
2329**Atomic service API**: This API can be used in atomic services since API version 12.
2330
2331**System capability**: SystemCapability.Multimedia.Image.Core
2332
2333**Parameters**
2334
2335| Name  | Type                | Mandatory| Description                          |
2336| -------- | -------------------- | ---- | ------------------------------ |
2337| rate     | number               | Yes  | Opacity rate. The value range is (0,1].  |
2338
2339**Error codes**
2340
2341For details about the error codes, see [Image Error Codes](errorcode-image.md).
2342
2343| ID| Error Message|
2344| ------- | --------------------------------------------|
2345|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
2346|  501    | Resource Unavailable |
2347
2348**Example**
2349
2350```ts
2351import { BusinessError } from '@kit.BasicServicesKit';
2352
2353async function OpacitySync() {
2354  let rate : number = 0.5;
2355  if (pixelMap != undefined) {
2356    pixelMap.opacitySync(rate);
2357  }
2358}
2359```
2360
2361### createAlphaPixelmap<sup>9+</sup>
2362
2363createAlphaPixelmap(): Promise\<PixelMap>
2364
2365Creates 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. It is invalid for YUV images.
2366
2367**Widget capability**: This API can be used in ArkTS widgets since API version 12.
2368
2369**Atomic service API**: This API can be used in atomic services since API version 11.
2370
2371**System capability**: SystemCapability.Multimedia.Image.Core
2372
2373**Return value**
2374
2375| Type                            | Description                       |
2376| -------------------------------- | --------------------------- |
2377| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the PixelMap object.|
2378
2379**Example**
2380
2381```ts
2382import { BusinessError } from '@kit.BasicServicesKit';
2383
2384async function CreateAlphaPixelmap() {
2385  if (pixelMap != undefined) {
2386    pixelMap.createAlphaPixelmap().then((alphaPixelMap: image.PixelMap) => {
2387      console.info('Succeeded in creating alpha pixelmap.');
2388    }).catch((error: BusinessError) => {
2389      console.error(`Failed to create alpha pixelmap. code is ${error.code}, message is ${error.message}`);
2390    })
2391  }
2392}
2393```
2394
2395### createAlphaPixelmap<sup>9+</sup>
2396
2397createAlphaPixelmap(callback: AsyncCallback\<PixelMap>): void
2398
2399Creates a PixelMap object that contains only the alpha channel information. This object can be used for the shadow effect. This API uses an asynchronous callback to return the result. It is invalid for YUV images.
2400
2401**Widget capability**: This API can be used in ArkTS widgets since API version 12.
2402
2403**Atomic service API**: This API can be used in atomic services since API version 11.
2404
2405**System capability**: SystemCapability.Multimedia.Image.Core
2406
2407**Parameters**
2408
2409| Name  | Type                    | Mandatory| Description                    |
2410| -------- | ------------------------ | ---- | ------------------------ |
2411| callback | AsyncCallback\<[PixelMap](#pixelmap7)> | Yes  |  Callback used to return the result. If the operation is successful, **err** is undefined and **data** is the PixelMap object obtained; otherwise, **err** is an error object.|
2412
2413**Example**
2414
2415```ts
2416import { BusinessError } from '@kit.BasicServicesKit';
2417
2418async function CreateAlphaPixelmap() {
2419  if (pixelMap != undefined) {
2420    pixelMap.createAlphaPixelmap((err: BusinessError, alphaPixelMap: image.PixelMap) => {
2421      if (alphaPixelMap == undefined) {
2422        console.error(`Failed to obtain new pixel map. code is ${err.code}, message is ${err.message}`);
2423        return;
2424      } else {
2425        console.info('Succeeded in obtaining new pixel map.');
2426      }
2427    })
2428  }
2429}
2430```
2431
2432### createAlphaPixelmapSync<sup>12+</sup>
2433
2434createAlphaPixelmapSync(): PixelMap
2435
2436Creates 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. It is invalid for YUV images.
2437
2438**Atomic service API**: This API can be used in atomic services since API version 12.
2439
2440**System capability**: SystemCapability.Multimedia.Image.Core
2441
2442**Return value**
2443
2444| Type                            | Description                 |
2445| -------------------------------- | --------------------- |
2446| [PixelMap](#pixelmap7) | PixelMap object. If the operation fails, an error is thrown.|
2447
2448**Error codes**
2449
2450For details about the error codes, see [Image Error Codes](errorcode-image.md).
2451
2452| ID| Error Message|
2453| ------- | --------------------------------------------|
2454|  401    | Parameter error. Possible causes: 1.Parameter verification failed |
2455|  501    | Resource Unavailable |
2456
2457**Example**
2458
2459```ts
2460import { BusinessError } from '@kit.BasicServicesKit';
2461
2462async function CreateAlphaPixelmapSync() {
2463  if (pixelMap != undefined) {
2464    let pixelmap : image.PixelMap = pixelMap.createAlphaPixelmapSync();
2465    return pixelmap;
2466  }
2467  return undefined;
2468}
2469```
2470
2471### scale<sup>9+</sup>
2472
2473scale(x: number, y: number, callback: AsyncCallback\<void>): void
2474
2475Scales this image based on the scale factors of the width and height. This API uses an asynchronous callback to return the result.
2476
2477> **NOTE**
2478>
2479> You are advised to set the scale factors to non-negative numbers to avoid a flipping effect.
2480>
2481> Scale factors of the width and height = Width and height of the resized image/Width and height of the original image
2482
2483**Widget capability**: This API can be used in ArkTS widgets since API version 12.
2484
2485**Atomic service API**: This API can be used in atomic services since API version 11.
2486
2487**System capability**: SystemCapability.Multimedia.Image.Core
2488
2489**Parameters**
2490
2491| Name  | Type                | Mandatory| Description                           |
2492| -------- | -------------------- | ---- | ------------------------------- |
2493| x        | number               | Yes  | Scale factor of the width.|
2494| y        | number               | Yes  | Scale factor of the height.|
2495| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
2496
2497**Example**
2498
2499```ts
2500import { BusinessError } from '@kit.BasicServicesKit';
2501
2502async function Scale() {
2503  let scaleX: number = 2.0;
2504  let scaleY: number = 1.0;
2505  if (pixelMap != undefined) {
2506    pixelMap.scale(scaleX, scaleY, (err: BusinessError) => {
2507      if (err) {
2508        console.error(`Failed to scale pixelmap. code is ${err.code}, message is ${err.message}`);
2509        return;
2510      } else {
2511        console.info("Succeeded in scaling pixelmap.");
2512      }
2513    })
2514  }
2515}
2516```
2517
2518### scale<sup>9+</sup>
2519
2520scale(x: number, y: number): Promise\<void>
2521
2522Scales this image based on the scale factors of the width and height. This API uses a promise to return the result.
2523
2524> **NOTE**
2525>
2526> You are advised to set the scale factors to non-negative numbers to avoid a flipping effect.
2527>
2528> Scale factors of the width and height = Width and height of the resized image/Width and height of the original image
2529
2530**Widget capability**: This API can be used in ArkTS widgets since API version 12.
2531
2532**Atomic service API**: This API can be used in atomic services since API version 11.
2533
2534**System capability**: SystemCapability.Multimedia.Image.Core
2535
2536**Parameters**
2537
2538| Name| Type  | Mandatory| Description                           |
2539| ------ | ------ | ---- | ------------------------------- |
2540| x      | number | Yes  | Scale factor of the width.|
2541| y      | number | Yes  | Scale factor of the height.|
2542
2543**Return value**
2544
2545| Type          | Description                       |
2546| -------------- | --------------------------- |
2547| Promise\<void> |  Promise that returns no value.|
2548
2549**Example**
2550
2551```ts
2552import { BusinessError } from '@kit.BasicServicesKit';
2553
2554async function Scale() {
2555  let scaleX: number = 2.0;
2556  let scaleY: number = 1.0;
2557  if (pixelMap != undefined) {
2558    pixelMap.scale(scaleX, scaleY).then(() => {
2559      console.info('Succeeded in scaling pixelmap.');
2560    }).catch((err: BusinessError) => {
2561      console.error(`Failed to scale pixelmap. code is ${err.code}, message is ${err.message}`);
2562
2563    })
2564  }
2565}
2566```
2567
2568### scaleSync<sup>12+</sup>
2569
2570scaleSync(x: number, y: number): void
2571
2572Scales this image based on the scale factors of the width and height. This API returns the result synchronously.
2573
2574> **NOTE**
2575>
2576> You are advised to set the scale factors to non-negative numbers to avoid a flipping effect.
2577>
2578> Scale factors of the width and height = Width and height of the resized image/Width and height of the original image
2579
2580**Atomic service API**: This API can be used in atomic services since API version 12.
2581
2582**System capability**: SystemCapability.Multimedia.Image.Core
2583
2584**Parameters**
2585
2586| Name| Type  | Mandatory| Description                           |
2587| ------ | ------ | ---- | ------------------------------- |
2588| x      | number | Yes  | Scale factor of the width.|
2589| y      | number | Yes  | Scale factor of the height.|
2590
2591**Error codes**
2592
2593For details about the error codes, see [Image Error Codes](errorcode-image.md).
2594
2595| ID| Error Message|
2596| ------- | --------------------------------------------|
2597|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
2598|  501    | Resource Unavailable |
2599
2600**Example**
2601
2602```ts
2603import { BusinessError } from '@kit.BasicServicesKit';
2604
2605async function ScaleSync() {
2606  let scaleX: number = 2.0;
2607  let scaleY: number = 1.0;
2608  if (pixelMap != undefined) {
2609    pixelMap.scaleSync(scaleX, scaleY);
2610  }
2611}
2612```
2613
2614### scale<sup>12+</sup>
2615
2616scale(x: number, y: number, level: AntiAliasingLevel): Promise\<void>
2617
2618Scales this image based on the specified anti-aliasing level and the scale factors for the width and height. This API uses a promise to return the result.
2619
2620> **NOTE**
2621>
2622> You are advised to set the scale factors to non-negative numbers to avoid a flipping effect.
2623>
2624> Scale factors of the width and height = Width and height of the resized image/Width and height of the original image
2625
2626**Widget capability**: This API can be used in ArkTS widgets since API version 12.
2627
2628**Atomic service API**: This API can be used in atomic services since API version 12.
2629
2630**System capability**: SystemCapability.Multimedia.Image.Core
2631
2632**Parameters**
2633
2634| Name| Type  | Mandatory| Description                           |
2635| ------ | ------ | ---- | ------------------------------- |
2636| x      | number | Yes  | Scale factor of the width.|
2637| y      | number | Yes  | Scale factor of the height.|
2638| level  | [AntiAliasingLevel](#antialiasinglevel12) | Yes  | Anti-aliasing level.|
2639
2640**Return value**
2641
2642| Type          | Description                       |
2643| -------------- | --------------------------- |
2644| Promise\<void> |  Promise that returns no value.|
2645
2646**Error codes**
2647
2648For details about the error codes, see [Image Error Codes](errorcode-image.md).
2649
2650| ID| Error Message|
2651| ------- | --------------------------------------------|
2652|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
2653|  501    | Resource Unavailable |
2654
2655**Example**
2656
2657```ts
2658import { BusinessError } from '@kit.BasicServicesKit';
2659
2660async function Scale() {
2661  let scaleX: number = 2.0;
2662  let scaleY: number = 1.0;
2663  if (pixelMap != undefined) {
2664    pixelMap.scale(scaleX, scaleY, image.AntiAliasingLevel.LOW).then(() => {
2665      console.info('Succeeded in scaling pixelmap.');
2666    }).catch((err: BusinessError) => {
2667      console.error(`Failed to scale pixelmap. code is ${err.code}, message is ${err.message}`);
2668
2669    })
2670  }
2671}
2672```
2673
2674### scaleSync<sup>12+</sup>
2675
2676scaleSync(x: number, y: number, level: AntiAliasingLevel): void
2677
2678Scales this image based on the specified anti-aliasing level and the scale factors for the width and height. This API returns the result synchronously.
2679
2680> **NOTE**
2681>
2682> You are advised to set the scale factors to non-negative numbers to avoid a flipping effect.
2683>
2684> Scale factors of the width and height = Width and height of the resized image/Width and height of the original image
2685
2686**Atomic service API**: This API can be used in atomic services since API version 12.
2687
2688**System capability**: SystemCapability.Multimedia.Image.Core
2689
2690**Parameters**
2691
2692| Name| Type  | Mandatory| Description                           |
2693| ------ | ------ | ---- | ------------------------------- |
2694| x      | number | Yes  | Scale factor of the width.|
2695| y      | number | Yes  | Scale factor of the height.|
2696| level  | [AntiAliasingLevel](#antialiasinglevel12) | Yes  | Anti-aliasing level.|
2697
2698**Error codes**
2699
2700For details about the error codes, see [Image Error Codes](errorcode-image.md).
2701
2702| ID| Error Message|
2703| ------- | --------------------------------------------|
2704|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
2705|  501    | Resource Unavailable |
2706
2707**Example**
2708
2709```ts
2710import { BusinessError } from '@kit.BasicServicesKit';
2711
2712async function ScaleSync() {
2713  let scaleX: number = 2.0;
2714  let scaleY: number = 1.0;
2715  if (pixelMap != undefined) {
2716    pixelMap.scaleSync(scaleX, scaleY, image.AntiAliasingLevel.LOW);
2717  }
2718}
2719```
2720
2721### createScaledPixelMap<sup>18+</sup>
2722
2723createScaledPixelMap(x: number, y: number, level?: AntiAliasingLevel): Promise\<PixelMap>
2724
2725Creates an image that has been resized based on the specified anti-aliasing level and the scale factors of the width and height. This API uses a promise to return the result.
2726
2727**System capability**: SystemCapability.Multimedia.Image.Core
2728
2729**Parameters**
2730
2731| Name| Type  | Mandatory| Description                           |
2732| ------ | ------ | ---- | ------------------------------- |
2733| x      | number | Yes  | Scale factor of the width.|
2734| y      | number | Yes  | Scale factor of the height.|
2735| level  | [AntiAliasingLevel](#antialiasinglevel12) | No  | Anti-aliasing level.|
2736
2737**Return value**
2738
2739| Type          | Description                       |
2740| -------------- | --------------------------- |
2741| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the PixelMap object.|
2742
2743**Error codes**
2744
2745For details about the error codes, see [Image Error Codes](errorcode-image.md).
2746
2747| ID| Error Message|
2748| ------- | --------------------------------------------|
2749|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
2750|  501    | Resource Unavailable |
2751
2752**Example**
2753
2754```ts
2755import { BusinessError } from '@kit.BasicServicesKit';
2756
2757async function CreateScaledPixelMap() {
2758  let scaleX: number = 2.0;
2759  let scaleY: number = 1.0;
2760  if (pixelMap != undefined) {
2761      pixelMap.createScaledPixelMap(scaleX, scaleY, image.AntiAliasingLevel.LOW).then((scaledPixelMap: image.PixelMap) => {
2762      console.info('Succeeded in creating scaledPixelMap.');
2763    }).catch((error: BusinessError) => {
2764      console.error(`Failed to create scaledPixelMap. Error code is ${error.code}, error message is ${error.message}`);
2765    })
2766  }
2767}
2768```
2769
2770### createScaledPixelMapSync<sup>18+</sup>
2771
2772createScaledPixelMapSync(x: number, y: number, level?: AntiAliasingLevel): PixelMap
2773
2774Creates an image that has been resized based on the specified anti-aliasing level and the scale factors of the width and height. This API returns the result synchronously.
2775
2776**System capability**: SystemCapability.Multimedia.Image.Core
2777
2778**Parameters**
2779
2780| Name| Type  | Mandatory| Description                           |
2781| ------ | ------ | ---- | ------------------------------- |
2782| x      | number | Yes  | Scale factor of the width.|
2783| y      | number | Yes  | Scale factor of the height.|
2784| level  | [AntiAliasingLevel](#antialiasinglevel12) | No  | Anti-aliasing level.|
2785
2786**Return value**
2787
2788| Type                            | Description                 |
2789| -------------------------------- | --------------------- |
2790| [PixelMap](#pixelmap7) | PixelMap object. If the operation fails, an error is thrown.|
2791
2792**Error codes**
2793
2794For details about the error codes, see [Image Error Codes](errorcode-image.md).
2795
2796| ID| Error Message|
2797| ------- | --------------------------------------------|
2798|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
2799|  501    | Resource Unavailable |
2800
2801**Example**
2802
2803```ts
2804import { BusinessError } from '@kit.BasicServicesKit';
2805
2806async function CreateScaledPixelMapSync() {
2807  let scaleX: number = 2.0;
2808  let scaleY: number = 1.0;
2809  if (pixelMap != undefined) {
2810    let scaledPixelMap = pixelMap.createScaledPixelMapSync(scaleX, scaleY, image.AntiAliasingLevel.LOW);
2811  }
2812}
2813```
2814
2815### clone<sup>18+</sup>
2816
2817clone(): Promise\<PixelMap>
2818
2819Copies this PixelMap object. This API uses a promise to return the result.
2820
2821**System capability**: SystemCapability.Multimedia.Image.Core
2822
2823**Return value**
2824
2825| Type                            | Description                 |
2826| -------------------------------- | --------------------------- |
2827| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the PixelMap object.|
2828
2829**Error codes**
2830
2831For details about the error codes, see [Image Error Codes](errorcode-image.md).
2832
2833| ID| Error Message|
2834| ------- | --------------------------------------------|
2835| 501 | Resource unavailable. |
2836| 62980102 | Image malloc abnormal. This status code is thrown when an error occurs during the process of copying data. |
2837| 62980103 | Image YUV And ASTC types are not supported. |
2838| 62980104 | Image initialization abnormal. This status code is thrown when an error occurs during the process of createing empty pixelmap. |
2839| 62980106 | The image data is to large. This status code is thrown when an error occurs during the process of checking size. |
2840
2841**Example**
2842
2843```ts
2844import { BusinessError } from '@kit.BasicServicesKit';
2845
2846async function Demo() {
2847  if (pixelMap != undefined) {
2848    pixelMap.clone().then((clonePixelMap: image.PixelMap) => {
2849      console.info('Succeeded clone pixelmap.');
2850    }).catch((error: BusinessError) => {
2851      console.error(`Failed to clone pixelmap. code is ${error.code}, message is ${error.message}`);
2852    })
2853  }
2854}
2855```
2856
2857### cloneSync<sup>18+</sup>
2858
2859cloneSync(): PixelMap
2860
2861Copies this PixelMap object. This API returns the result synchronously.
2862
2863**System capability**: SystemCapability.Multimedia.Image.Core
2864
2865**Return value**
2866
2867| Type                            | Description                 |
2868| -------------------------------- | --------------------------- |
2869| [PixelMap](#pixelmap7) | PixelMap object. If the operation fails, an error is thrown.|
2870
2871**Error codes**
2872
2873For details about the error codes, see [Image Error Codes](errorcode-image.md).
2874
2875| ID| Error Message|
2876| ------- | --------------------------------------------|
2877| 501 | Resource unavailable. |
2878| 62980102 | Image malloc abnormal. This status code is thrown when an error occurs during the process of copying data. |
2879| 62980103 | Image YUV And ASTC types are not supported. |
2880| 62980104 | Image initialization abnormal. This status code is thrown when an error occurs during the process of createing empty pixelmap. |
2881| 62980106 | The image data is to large. This status code is thrown when an error occurs during the process of checking size. |
2882
2883**Example**
2884
2885```ts
2886import { BusinessError } from '@kit.BasicServicesKit';
2887
2888async function Demo(pixelMap: image.PixelMap) {
2889  if (pixelMap != undefined) {
2890    try {
2891      let clonedPixelMap = pixelMap.cloneSync();
2892    } catch(e) {
2893      let error = e as BusinessError;
2894      console.error(`clone pixelmap error. code is ${error.code}, message is ${error.message}`);
2895    }
2896  }
2897}
2898```
2899
2900### translate<sup>9+</sup>
2901
2902translate(x: number, y: number, callback: AsyncCallback\<void>): void
2903
2904Translates this image based on given coordinates. This API uses an asynchronous callback to return the result.
2905
2906The size of the translated image is changed to width+X and height+Y. It is recommended that the new width and height not exceed the width and height of the screen.
2907
2908**Widget capability**: This API can be used in ArkTS widgets since API version 12.
2909
2910**Atomic service API**: This API can be used in atomic services since API version 11.
2911
2912**System capability**: SystemCapability.Multimedia.Image.Core
2913
2914**Parameters**
2915
2916| Name  | Type                | Mandatory| Description                         |
2917| -------- | -------------------- | ---- | ----------------------------- |
2918| x        | number               | Yes  | X coordinate to translate, in px.|
2919| y        | number               | Yes  | Y coordinate to translate, in px.|
2920| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
2921
2922**Example**
2923
2924```ts
2925import { BusinessError } from '@kit.BasicServicesKit';
2926
2927async function Translate() {
2928  let translateX: number = 50.0;
2929  let translateY: number = 10.0;
2930  if (pixelMap != undefined) {
2931    pixelMap.translate(translateX, translateY, (err: BusinessError) => {
2932      if (err) {
2933        console.error(`Failed to translate pixelmap. code is ${err.code}, message is ${err.message}`);
2934        return;
2935      } else {
2936        console.info("Succeeded in translating pixelmap.");
2937      }
2938    })
2939  }
2940}
2941```
2942
2943### translate<sup>9+</sup>
2944
2945translate(x: number, y: number): Promise\<void>
2946
2947Translates this image based on given coordinates. This API uses a promise to return the result.
2948
2949The size of the translated image is changed to width+X and height+Y. It is recommended that the new width and height not exceed the width and height of the screen.
2950
2951**Widget capability**: This API can be used in ArkTS widgets since API version 12.
2952
2953**Atomic service API**: This API can be used in atomic services since API version 11.
2954
2955**System capability**: SystemCapability.Multimedia.Image.Core
2956
2957**Parameters**
2958
2959| Name| Type  | Mandatory| Description       |
2960| ------ | ------ | ---- | ----------- |
2961| x      | number | Yes  | X coordinate to translate, in px.|
2962| y      | number | Yes  | Y coordinate to translate, in px.|
2963
2964**Return value**
2965
2966| Type          | Description                       |
2967| -------------- | --------------------------- |
2968| Promise\<void> |  Promise that returns no value.|
2969
2970**Example**
2971
2972```ts
2973import { BusinessError } from '@kit.BasicServicesKit';
2974
2975async function Translate() {
2976  let translateX: number = 50.0;
2977  let translateY: number = 10.0;
2978  if (pixelMap != undefined) {
2979    pixelMap.translate(translateX, translateY).then(() => {
2980      console.info('Succeeded in translating pixelmap.');
2981    }).catch((err: BusinessError) => {
2982      console.error(`Failed to translate pixelmap. code is ${err.code}, message is ${err.message}`);
2983    })
2984  }
2985}
2986```
2987
2988### translateSync<sup>12+</sup>
2989
2990translateSync(x: number, y: number): void
2991
2992Translates this image based on given coordinates. This API returns the result synchronously.
2993
2994The size of the translated image is changed to width+X and height+Y. It is recommended that the new width and height not exceed the width and height of the screen.
2995
2996**Atomic service API**: This API can be used in atomic services since API version 12.
2997
2998**System capability**: SystemCapability.Multimedia.Image.Core
2999
3000**Parameters**
3001
3002| Name  | Type                | Mandatory| Description                           |
3003| -------- | -------------------- | ---- | ------------------------------- |
3004| x        | number               | Yes  | X coordinate to translate, in px.|
3005| y        | number               | Yes  | Y coordinate to translate, in px.|
3006
3007**Error codes**
3008
3009For details about the error codes, see [Image Error Codes](errorcode-image.md).
3010
3011| ID| Error Message|
3012| ------- | --------------------------------------------|
3013|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
3014|  501    | Resource Unavailable |
3015
3016**Example**
3017
3018```ts
3019import { BusinessError } from '@kit.BasicServicesKit';
3020
3021async function TranslateSync() {
3022  let translateX : number = 50.0;
3023  let translateY : number = 10.0;
3024  if (pixelMap != undefined) {
3025    pixelMap.translateSync(translateX, translateY);
3026  }
3027}
3028```
3029
3030### rotate<sup>9+</sup>
3031
3032rotate(angle: number, callback: AsyncCallback\<void>): void
3033
3034Rotates this image based on a given angle. This API uses an asynchronous callback to return the result.
3035
3036> **NOTE**
3037>
3038> The allowable range for image rotation angles is between 0 and 360 degrees. Angles outside this range are automatically adjusted according to the 360-degree cycle. For example, an angle of -100 degrees will produce the same result as 260 degrees.
3039>
3040> If the rotation angle is not an integer multiple of 90 degrees, the image size will change after rotation.
3041
3042**Widget capability**: This API can be used in ArkTS widgets since API version 12.
3043
3044**Atomic service API**: This API can be used in atomic services since API version 11.
3045
3046**System capability**: SystemCapability.Multimedia.Image.Core
3047
3048**Parameters**
3049
3050| Name  | Type                | Mandatory| Description                         |
3051| -------- | -------------------- | ---- | ----------------------------- |
3052| angle    | number               | Yes  | Angle to rotate.|
3053| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
3054
3055**Example**
3056
3057```ts
3058import { BusinessError } from '@kit.BasicServicesKit';
3059
3060async function Rotate() {
3061  let angle: number = 90.0;
3062  if (pixelMap != undefined) {
3063    pixelMap.rotate(angle, (err: BusinessError) => {
3064      if (err) {
3065        console.error(`Failed to rotate pixelmap. code is ${err.code}, message is ${err.message}`);
3066        return;
3067      } else {
3068        console.info("Succeeded in rotating pixelmap.");
3069      }
3070    })
3071  }
3072}
3073```
3074
3075### rotate<sup>9+</sup>
3076
3077rotate(angle: number): Promise\<void>
3078
3079Rotates this image based on a given angle. This API uses a promise to return the result.
3080
3081> **NOTE**
3082>
3083> The allowable range for image rotation angles is between 0 and 360 degrees. Angles outside this range are automatically adjusted according to the 360-degree cycle. For example, an angle of -100 degrees will produce the same result as 260 degrees.
3084>
3085> If the rotation angle is not an integer multiple of 90 degrees, the image size will change after rotation.
3086
3087**Widget capability**: This API can be used in ArkTS widgets since API version 12.
3088
3089**Atomic service API**: This API can be used in atomic services since API version 11.
3090
3091**System capability**: SystemCapability.Multimedia.Image.Core
3092
3093**Parameters**
3094
3095| Name| Type  | Mandatory| Description                         |
3096| ------ | ------ | ---- | ----------------------------- |
3097| angle  | number | Yes  | Angle to rotate.|
3098
3099**Return value**
3100
3101| Type          | Description                       |
3102| -------------- | --------------------------- |
3103| Promise\<void> |  Promise that returns no value.|
3104
3105**Example**
3106
3107```ts
3108import { BusinessError } from '@kit.BasicServicesKit';
3109
3110async function Rotate() {
3111  let angle: number = 90.0;
3112  if (pixelMap != undefined) {
3113    pixelMap.rotate(angle).then(() => {
3114      console.info('Succeeded in rotating pixelmap.');
3115    }).catch((err: BusinessError) => {
3116      console.error(`Failed to rotate pixelmap. code is ${err.code}, message is ${err.message}`);
3117    })
3118  }
3119}
3120```
3121
3122### rotateSync<sup>12+</sup>
3123
3124rotateSync(angle: number): void
3125
3126Rotates this image based on a given angle. This API returns the result synchronously.
3127
3128> **NOTE**
3129>
3130> The allowable range for image rotation angles is between 0 and 360 degrees. Angles outside this range are automatically adjusted according to the 360-degree cycle. For example, an angle of -100 degrees will produce the same result as 260 degrees.
3131>
3132> If the rotation angle is not an integer multiple of 90 degrees, the image size will change after rotation.
3133
3134**Atomic service API**: This API can be used in atomic services since API version 12.
3135
3136**System capability**: SystemCapability.Multimedia.Image.Core
3137
3138**Parameters**
3139
3140| Name  | Type                | Mandatory| Description                         |
3141| -------- | -------------------- | ---- | ----------------------------- |
3142| angle    | number               | Yes  | Angle to rotate.|
3143
3144**Error codes**
3145
3146For details about the error codes, see [Image Error Codes](errorcode-image.md).
3147
3148| ID| Error Message|
3149| ------- | --------------------------------------------|
3150|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
3151|  501    | Resource Unavailable |
3152
3153**Example**
3154
3155```ts
3156import { BusinessError } from '@kit.BasicServicesKit';
3157
3158async function RotateSync() {
3159  let angle : number = 90.0;
3160  if (pixelMap != undefined) {
3161    pixelMap.rotateSync(angle);
3162  }
3163}
3164```
3165
3166### flip<sup>9+</sup>
3167
3168flip(horizontal: boolean, vertical: boolean, callback: AsyncCallback\<void>): void
3169
3170Flips this image horizontally or vertically, or both. This API uses an asynchronous callback to return the result.
3171
3172**Widget capability**: This API can be used in ArkTS widgets since API version 12.
3173
3174**Atomic service API**: This API can be used in atomic services since API version 11.
3175
3176**System capability**: SystemCapability.Multimedia.Image.Core
3177
3178**Parameters**
3179
3180| Name    | Type                | Mandatory| Description                         |
3181| ---------- | -------------------- | ---- | ----------------------------- |
3182| horizontal | boolean              | Yes  | Whether to flip the image horizontally. The value **true** means to flip the image horizontally, and **false** means the opposite.           |
3183| vertical   | boolean              | Yes  | Whether to flip the image vertically. The value **true** means to flip the image vertically, and **false** means the opposite.           |
3184| callback   | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
3185
3186**Example**
3187
3188```ts
3189import { BusinessError } from '@kit.BasicServicesKit';
3190
3191async function Flip() {
3192  let horizontal: boolean = true;
3193  let vertical: boolean = false;
3194  if (pixelMap != undefined) {
3195    pixelMap.flip(horizontal, vertical, (err: BusinessError) => {
3196      if (err) {
3197        console.error(`Failed to flip pixelmap. code is ${err.code}, message is ${err.message}`);
3198        return;
3199      } else {
3200        console.info("Succeeded in flipping pixelmap.");
3201      }
3202    })
3203  }
3204}
3205```
3206
3207### flip<sup>9+</sup>
3208
3209flip(horizontal: boolean, vertical: boolean): Promise\<void>
3210
3211Flips this image horizontally or vertically, or both. This API uses a promise to return the result.
3212
3213**Widget capability**: This API can be used in ArkTS widgets since API version 12.
3214
3215**Atomic service API**: This API can be used in atomic services since API version 11.
3216
3217**System capability**: SystemCapability.Multimedia.Image.Core
3218
3219**Parameters**
3220
3221| Name    | Type   | Mandatory| Description     |
3222| ---------- | ------- | ---- | --------- |
3223| horizontal | boolean              | Yes  | Whether to flip the image horizontally. The value **true** means to flip the image horizontally, and **false** means the opposite.           |
3224| vertical   | boolean              | Yes  | Whether to flip the image vertically. The value **true** means to flip the image vertically, and **false** means the opposite.           |
3225
3226**Return value**
3227
3228| Type          | Description                       |
3229| -------------- | --------------------------- |
3230| Promise\<void> |  Promise that returns no value.|
3231
3232**Example**
3233
3234```ts
3235import { BusinessError } from '@kit.BasicServicesKit';
3236
3237async function Flip() {
3238  let horizontal: boolean = true;
3239  let vertical: boolean = false;
3240  if (pixelMap != undefined) {
3241    pixelMap.flip(horizontal, vertical).then(() => {
3242      console.info('Succeeded in flipping pixelmap.');
3243    }).catch((err: BusinessError) => {
3244      console.error(`Failed to flip pixelmap. code is ${err.code}, message is ${err.message}`);
3245    })
3246  }
3247}
3248```
3249
3250### flipSync<sup>12+</sup>
3251
3252flipSync(horizontal: boolean, vertical: boolean): void
3253
3254Flips this image horizontally or vertically, or both. This API returns the result synchronously.
3255
3256**Atomic service API**: This API can be used in atomic services since API version 12.
3257
3258**System capability**: SystemCapability.Multimedia.Image.Core
3259
3260**Parameters**
3261
3262| Name    | Type                | Mandatory| Description                         |
3263| ---------- | -------------------- | ---- | ----------------------------- |
3264| horizontal | boolean              | Yes  | Whether to flip the image horizontally. The value **true** means to flip the image horizontally, and **false** means the opposite.           |
3265| vertical   | boolean              | Yes  | Whether to flip the image vertically. The value **true** means to flip the image vertically, and **false** means the opposite.           |
3266
3267**Error codes**
3268
3269For details about the error codes, see [Image Error Codes](errorcode-image.md).
3270
3271| ID| Error Message|
3272| ------- | --------------------------------------------|
3273|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
3274|  501    | Resource Unavailable |
3275
3276**Example**
3277
3278```ts
3279import { BusinessError } from '@kit.BasicServicesKit';
3280
3281async function FlipSync() {
3282  let horizontal : boolean = true;
3283  let vertical : boolean = false;
3284  if (pixelMap != undefined) {
3285    pixelMap.flipSync(horizontal, vertical);
3286  }
3287}
3288```
3289
3290### crop<sup>9+</sup>
3291
3292crop(region: Region, callback: AsyncCallback\<void>): void
3293
3294Crops this image based on a given size. This API uses an asynchronous callback to return the result.
3295
3296**Widget capability**: This API can be used in ArkTS widgets since API version 12.
3297
3298**Atomic service API**: This API can be used in atomic services since API version 11.
3299
3300**System capability**: SystemCapability.Multimedia.Image.Core
3301
3302**Parameters**
3303
3304| Name  | Type                | Mandatory| Description                         |
3305| -------- | -------------------- | ---- | ----------------------------- |
3306| region   | [Region](#region8)   | Yes  | Size of the image after cropping. The value cannot exceed the width or height of the image.|
3307| callback | AsyncCallback\<void> | Yes  |  Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
3308
3309**Example**
3310
3311```ts
3312import { BusinessError } from '@kit.BasicServicesKit';
3313
3314async function Crop() {
3315  let region: image.Region = { x: 0, y: 0, size: { height: 100, width: 100 } };
3316  if (pixelMap != undefined) {
3317    pixelMap.crop(region, (err: BusinessError) => {
3318      if (err) {
3319        console.error(`Failed to crop pixelmap. code is ${err.code}, message is ${err.message}`);
3320        return;
3321      } else {
3322        console.info("Succeeded in cropping pixelmap.");
3323      }
3324    })
3325  }
3326}
3327```
3328
3329### crop<sup>9+</sup>
3330
3331crop(region: Region): Promise\<void>
3332
3333Crops this image based on a given size. This API uses a promise to return the result.
3334
3335**Widget capability**: This API can be used in ArkTS widgets since API version 12.
3336
3337**Atomic service API**: This API can be used in atomic services since API version 11.
3338
3339**System capability**: SystemCapability.Multimedia.Image.Core
3340
3341**Parameters**
3342
3343| Name| Type              | Mandatory| Description       |
3344| ------ | ------------------ | ---- | ----------- |
3345| region | [Region](#region8) | Yes  | Size of the image after cropping. The value cannot exceed the width or height of the image.|
3346
3347**Return value**
3348
3349| Type          | Description                       |
3350| -------------- | --------------------------- |
3351| Promise\<void> |  Promise that returns no value.|
3352
3353**Example**
3354
3355```ts
3356import { BusinessError } from '@kit.BasicServicesKit';
3357
3358async function Crop() {
3359  let region: image.Region = { x: 0, y: 0, size: { height: 100, width: 100 } };
3360  if (pixelMap != undefined) {
3361    pixelMap.crop(region).then(() => {
3362      console.info('Succeeded in cropping pixelmap.');
3363    }).catch((err: BusinessError) => {
3364      console.error(`Failed to crop pixelmap. code is ${err.code}, message is ${err.message}`);
3365
3366    });
3367  }
3368}
3369```
3370
3371### cropSync<sup>12+</sup>
3372
3373cropSync(region: Region): void
3374
3375Crops this image based on a given size. This API returns the result synchronously.
3376
3377**Atomic service API**: This API can be used in atomic services since API version 12.
3378
3379**System capability**: SystemCapability.Multimedia.Image.Core
3380
3381**Parameters**
3382
3383| Name  | Type                | Mandatory| Description                         |
3384| -------- | -------------------- | ---- | ----------------------------- |
3385| region   | [Region](#region8)   | Yes  | Size of the image after cropping. The value cannot exceed the width or height of the image.|
3386
3387**Error codes**
3388
3389For details about the error codes, see [Image Error Codes](errorcode-image.md).
3390
3391| ID| Error Message|
3392| ------- | --------------------------------------------|
3393|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
3394|  501    | Resource Unavailable |
3395
3396**Example**
3397
3398```ts
3399import { BusinessError } from '@kit.BasicServicesKit';
3400
3401async function CropSync() {
3402  let region : image.Region = { x: 0, y: 0, size: { height: 100, width: 100 } };
3403  if (pixelMap != undefined) {
3404    pixelMap.cropSync(region);
3405  }
3406}
3407```
3408
3409### getColorSpace<sup>10+</sup>
3410
3411getColorSpace(): colorSpaceManager.ColorSpaceManager
3412
3413Obtains the color space of this image.
3414
3415**System capability**: SystemCapability.Multimedia.Image.Core
3416
3417**Return value**
3418
3419| Type                               | Description            |
3420| ----------------------------------- | ---------------- |
3421| [colorSpaceManager.ColorSpaceManager](../apis-arkgraphics2d/js-apis-colorSpaceManager.md#colorspacemanager) | Color space obtained.|
3422
3423**Error codes**
3424
3425For details about the error codes, see [Image Error Codes](errorcode-image.md).
3426
3427| ID| Error Message|
3428| ------- | --------------------------------------------|
3429| 62980101| If the image data abnormal.            |
3430| 62980103| If the image data unsupport.             |
3431| 62980115| If the image parameter invalid.            |
3432
3433**Example**
3434
3435```ts
3436async function GetColorSpace() {
3437  if (pixelMap != undefined) {
3438    let csm = pixelMap.getColorSpace();
3439  }
3440}
3441```
3442
3443### setColorSpace<sup>10+</sup>
3444
3445setColorSpace(colorSpace: colorSpaceManager.ColorSpaceManager): void
3446
3447Sets the color space for this image.
3448
3449**System capability**: SystemCapability.Multimedia.Image.Core
3450
3451**Parameters**
3452
3453| Name    | Type                               | Mandatory| Description           |
3454| ---------- | ----------------------------------- | ---- | --------------- |
3455| colorSpace | [colorSpaceManager.ColorSpaceManager](../apis-arkgraphics2d/js-apis-colorSpaceManager.md#colorspacemanager) | Yes  | Color space to set.|
3456
3457**Error codes**
3458
3459For details about the error codes, see [Image Error Codes](errorcode-image.md).
3460
3461| ID| Error Message|
3462| ------- | --------------------------------------------|
3463| 62980111| The image source data is incomplete.        |
3464| 62980115| If the image parameter invalid.             |
3465
3466**Example**
3467
3468```ts
3469import { colorSpaceManager } from '@kit.ArkGraphics2D';
3470async function SetColorSpace() {
3471  let colorSpaceName = colorSpaceManager.ColorSpace.SRGB;
3472  let csm: colorSpaceManager.ColorSpaceManager = colorSpaceManager.create(colorSpaceName);
3473  if (pixelMap != undefined) {
3474    pixelMap.setColorSpace(csm);
3475  }
3476}
3477```
3478
3479### applyColorSpace<sup>11+</sup>
3480
3481applyColorSpace(targetColorSpace: colorSpaceManager.ColorSpaceManager, callback: AsyncCallback\<void>): void
3482
3483Performs color space conversion (CSC) on the image pixel color based on a given color space. This API uses an asynchronous callback to return the result.
3484
3485**System capability**: SystemCapability.Multimedia.Image.Core
3486
3487**Parameters**
3488
3489| Name  | Type                | Mandatory| Description                         |
3490| -------- | -------------------- | ---- | ----------------------------- |
3491| 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.|
3492| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
3493
3494**Error codes**
3495
3496For details about the error codes, see [Image Error Codes](errorcode-image.md).
3497
3498| ID| Error Message|
3499| ------- | ------------------------------------------|
3500| 401     | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
3501| 62980104| Failed to initialize the internal object. |
3502| 62980108| Failed to convert the color space.       |
3503| 62980115| Invalid image parameter.            |
3504
3505**Example**
3506
3507```ts
3508import { colorSpaceManager } from '@kit.ArkGraphics2D';
3509import { BusinessError } from '@kit.BasicServicesKit';
3510
3511async function ApplyColorSpace() {
3512  let colorSpaceName = colorSpaceManager.ColorSpace.SRGB;
3513  let targetColorSpace: colorSpaceManager.ColorSpaceManager = colorSpaceManager.create(colorSpaceName);
3514  if (pixelMap != undefined) {
3515    pixelMap.applyColorSpace(targetColorSpace, (error: BusinessError) => {
3516      if (error) {
3517        console.error(`Failed to apply color space for pixelmap object, error code is ${error}`);
3518        return;
3519      } else {
3520        console.info('Succeeded in applying color space for pixelmap object.');
3521      }
3522    })
3523  }
3524}
3525```
3526
3527### applyColorSpace<sup>11+</sup>
3528
3529applyColorSpace(targetColorSpace: colorSpaceManager.ColorSpaceManager): Promise\<void>
3530
3531Performs CSC on the image pixel color based on a given color space. This API uses a promise to return the result.
3532
3533**System capability**: SystemCapability.Multimedia.Image.Core
3534
3535**Parameters**
3536
3537| Name| Type              | Mandatory| Description       |
3538| ------ | ------------------ | ---- | ----------- |
3539| 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.|
3540
3541**Return value**
3542
3543| Type          | Description                       |
3544| -------------- | --------------------------- |
3545| Promise\<void> |  Promise that returns no value.|
3546
3547**Error codes**
3548
3549For details about the error codes, see [Image Error Codes](errorcode-image.md).
3550
3551| ID| Error Message|
3552| ------- | ------------------------------------------|
3553| 401     | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
3554| 62980104| Failed to initialize the internal object. |
3555| 62980108| Failed to convert the color space.       |
3556| 62980115| Invalid image parameter.            |
3557
3558**Example**
3559
3560```ts
3561import { colorSpaceManager } from '@kit.ArkGraphics2D';
3562import { BusinessError } from '@kit.BasicServicesKit';
3563
3564async function ApplyColorSpace() {
3565  let colorSpaceName = colorSpaceManager.ColorSpace.SRGB;
3566  let targetColorSpace: colorSpaceManager.ColorSpaceManager = colorSpaceManager.create(colorSpaceName);
3567  if (pixelMap != undefined) {
3568    pixelMap.applyColorSpace(targetColorSpace).then(() => {
3569      console.info('Succeeded in applying color space for pixelmap object.');
3570    }).catch((error: BusinessError) => {
3571      console.error(`Failed to apply color space for pixelmap object, error code is ${error}`);
3572    })
3573  }
3574}
3575```
3576
3577### toSdr<sup>12+<sup>
3578
3579toSdr(): Promise\<void>
3580
3581Converts an HDR image into an SDR image. This API uses a promise to return the result.
3582
3583**System capability**: SystemCapability.Multimedia.Image.Core
3584
3585**Return value**
3586
3587| Type          | Description                       |
3588| -------------- | --------------------------- |
3589| Promise\<void> |  Promise that returns no value.|
3590
3591**Error codes**
3592
3593For details about the error codes, see [Image Error Codes](errorcode-image.md).
3594
3595| ID| Error Message|
3596| ------- | --------------------------------------------|
3597| 62980137 | Invalid image operation.              |
3598
3599**Example**
3600
3601<!--code_no_check-->
3602```ts
3603import image from '@ohos.multimedia.image';
3604import resourceManager from '@ohos.resourceManager';
3605import { BusinessError } from '@kit.BasicServicesKit';
3606import { common } from '@kit.AbilityKit';
3607
3608// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
3609let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
3610// 'hdr.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
3611let img = context.resourceManager.getMediaContentSync($r('app.media.hdr'));
3612let imageSource = image.createImageSource(img.buffer.slice(0));
3613let decodingOptions: image.DecodingOptions = {
3614  desiredDynamicRange: image.DecodingDynamicRange.AUTO
3615};
3616let pixelmap = imageSource.createPixelMapSync(decodingOptions);
3617if (pixelmap != undefined) {
3618  console.info('Succeeded in creating pixelMap object.');
3619  pixelmap.toSdr().then(() => {
3620    let imageInfo = pixelmap.getImageInfoSync();
3621    console.info("after toSdr ,imageInfo isHdr:" + imageInfo.isHdr);
3622  }).catch((err: BusinessError) => {
3623    console.error(`Failed to set sdr. code is ${err.code}, message is ${err.message}`);
3624  });
3625} else {
3626  console.error('Failed to create pixelMap.');
3627}
3628```
3629
3630### getMetadata<sup>12+</sup>
3631
3632getMetadata(key: HdrMetadataKey): HdrMetadataValue
3633
3634Obtains the value of the metadata with a given key in this PixelMap.
3635
3636**System capability**: SystemCapability.Multimedia.Image.Core
3637
3638**Parameters**
3639
3640| Name       | Type                            | Mandatory| Description            |
3641| ------------- | -------------------------------- | ---- | ---------------- |
3642| key | [HdrMetadataKey](#hdrmetadatakey12) | Yes  | Key of the HDR metadata.|
3643
3644**Return value**
3645
3646| Type                             | Description                             |
3647| --------------------------------- | --------------------------------- |
3648| [HdrMetadataValue](#hdrmetadatavalue12) | Value of the metadata with the given key.|
3649
3650**Error codes**
3651
3652For details about the error codes, see [Image Error Codes](errorcode-image.md).
3653
3654| ID| Error Message|
3655| ------- | --------------------------------------------|
3656| 401| Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.          |
3657| 501 | Resource unavailable.          |
3658| 62980173 | The DMA memory does not exist.          |
3659| 62980302 | Memory copy failed. Possibly caused by invalid metadata value.          |
3660
3661**Example**
3662
3663<!--code_no_check-->
3664```ts
3665import { BusinessError } from '@kit.BasicServicesKit';
3666import { common } from '@kit.AbilityKit';
3667import image from '@ohos.multimedia.image';
3668
3669// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
3670let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
3671// Replace 'app.media.test' with a local HDR image.
3672let img = context.resourceManager.getMediaContentSync($r('app.media.test'));
3673let imageSource = image.createImageSource(img.buffer.slice(0));
3674let decodingOptions: image.DecodingOptions = {
3675  desiredDynamicRange: image.DecodingDynamicRange.AUTO
3676};
3677let pixelmap = imageSource.createPixelMapSync(decodingOptions);
3678if (pixelmap != undefined) {
3679  console.info('Succeeded in creating pixelMap object.');
3680  try {
3681    let staticMetadata = pixelmap.getMetadata(image.HdrMetadataKey.HDR_STATIC_METADATA);
3682    console.info("getmetadata:" + JSON.stringify(staticMetadata));
3683  } catch (e) {
3684    console.error('pixelmap create failed' + e);
3685  }
3686} else {
3687  console.error('Failed to create pixelMap.');
3688}
3689```
3690
3691### setMetadata<sup>12+</sup>
3692
3693setMetadata(key: HdrMetadataKey, value: HdrMetadataValue): Promise\<void>
3694
3695Sets the value for the metadata with a given key in this PixelMap.
3696
3697**System capability**: SystemCapability.Multimedia.Image.Core
3698
3699**Parameters**
3700
3701| Name       | Type                            | Mandatory| Description            |
3702| ------------- | -------------------------------- | ---- | ---------------- |
3703| key | [HdrMetadataKey](#hdrmetadatakey12) | Yes  | Key of the HDR metadata.|
3704| value | [HdrMetadataValue](#hdrmetadatavalue12) | Yes  | Value of the metadata.|
3705
3706**Return value**
3707
3708| Type          | Description                 |
3709| -------------- | --------------------- |
3710| Promise\<void> |  Promise that returns no value.|
3711
3712**Error codes**
3713
3714For details about the error codes, see [Image Error Codes](errorcode-image.md).
3715
3716| ID| Error Message|
3717| ------- | --------------------------------------------|
3718| 401|  Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.         |
3719| 501 | Resource unavailable.          |
3720| 62980173 | The DMA memory does not exist.          |
3721| 62980302 | Memory copy failed. Possibly caused by invalid metadata value.         |
3722
3723**Example**
3724
3725```ts
3726import image from '@ohos.multimedia.image';
3727import { BusinessError } from '@kit.BasicServicesKit';
3728
3729let staticMetadata: image.HdrStaticMetadata = {
3730  displayPrimariesX: [1.1, 1.1, 1.1],
3731  displayPrimariesY: [1.2, 1.2, 1.2],
3732  whitePointX: 1.1,
3733  whitePointY: 1.2,
3734  maxLuminance: 2.1,
3735  minLuminance: 1.0,
3736  maxContentLightLevel: 2.1,
3737  maxFrameAverageLightLevel: 2.1,
3738};
3739const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4.
3740let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } };
3741image.createPixelMap(color, opts).then((pixelMap: image.PixelMap) => {
3742  pixelMap.setMetadata(image.HdrMetadataKey.HDR_STATIC_METADATA, staticMetadata).then(() => {
3743    console.info('Succeeded in setting pixelMap metadata.');
3744  }).catch((error: BusinessError) => {
3745    console.error(`Failed to set the metadata.code ${error.code},message is ${error.message}`);
3746  })
3747}).catch((error: BusinessError) => {
3748  console.error(`Failed to create the PixelMap.code ${error.code},message is ${error.message}`);
3749})
3750
3751```
3752
3753### setTransferDetached<sup>12+<sup>
3754
3755setTransferDetached(detached: boolean): void
3756
3757Sets whether to detach from the original thread when this PixelMap is transmitted across threads. This API applies to the scenario where the PixelMap needs to be released immediately.
3758
3759**System capability**: SystemCapability.Multimedia.Image.Core
3760
3761**Parameters**
3762
3763| Name  | Type              | Mandatory| Description                         |
3764| ------- | ------------------ | ---- | ----------------------------- |
3765| detached | boolean   | Yes  | Whether to detach from the original thread. The value **true** means to detach from the original thread, and **false** means the opposite.|
3766
3767**Error codes**
3768
3769For details about the error codes, see [Image Error Codes](errorcode-image.md).
3770
3771| ID| Error Message|
3772| ------- | --------------------------------------------|
3773|  501    | Resource Unavailable |
3774
3775**Example**
3776
3777```ts
3778import { BusinessError } from '@kit.BasicServicesKit';
3779import { common } from '@kit.AbilityKit';
3780import image from '@ohos.multimedia.image';
3781import taskpool from '@ohos.taskpool';
3782
3783@Concurrent
3784// Child thread method.
3785async function loadPixelMap(rawFileDescriptor: number): Promise<PixelMap> {
3786  // Create an ImageSource instance.
3787  const imageSource = image.createImageSource(rawFileDescriptor);
3788  // Create a pixelMap.
3789  const pixelMap = imageSource.createPixelMapSync();
3790  // Release the ImageSource instance.
3791  imageSource.release();
3792  // Disconnect the reference of the original thread after the cross-thread transfer of the pixelMap is complete.
3793  pixelMap.setTransferDetached(true);
3794  // Return the pixelMap to the main thread.
3795  return pixelMap;
3796}
3797
3798@Component
3799struct Demo {
3800  @State pixelMap: PixelMap | undefined = undefined;
3801  // Main thread method.
3802  private loadImageFromThread(): void {
3803    let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
3804    const resourceMgr = context.resourceManager;
3805    // 'example.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
3806    resourceMgr.getRawFd('example.jpg').then(rawFileDescriptor => {
3807      taskpool.execute(loadPixelMap, rawFileDescriptor).then(pixelMap => {
3808        if (pixelMap) {
3809          this.pixelMap = pixelMap as PixelMap;
3810          console.log('Succeeded in creating pixelMap.');
3811          // The main thread releases the pixelMap. Because setTransferDetached has been called when the child thread returns pixelMap, the pixelMap can be released immediately.
3812          this.pixelMap.release();
3813        } else {
3814          console.error('Failed to create pixelMap.');
3815        }
3816      });
3817    });
3818  }
3819  build() {
3820    // ...
3821  }
3822}
3823```
3824
3825### marshalling<sup>10+</sup>
3826
3827marshalling(sequence: rpc.MessageSequence): void
3828
3829Marshals this PixelMap object and writes it to a MessageSequence object.
3830
3831**System capability**: SystemCapability.Multimedia.Image.Core
3832
3833**Parameters**
3834
3835| Name                | Type                                                 | Mandatory| Description                                    |
3836| ---------------------- | ------------------------------------------------------ | ---- | ---------------------------------------- |
3837| sequence               | [rpc.MessageSequence](../apis-ipc-kit/js-apis-rpc.md#messagesequence9)  | Yes  | MessageSequence object.                |
3838
3839**Error codes**
3840
3841For details about the error codes, see [Image Error Codes](errorcode-image.md).
3842
3843| ID| Error Message|
3844| ------- | --------------------------------------------|
3845| 62980115 | Invalid image parameter.              |
3846| 62980097 | IPC error. Possible cause: 1.IPC communication failed. 2. Image upload exception. 3. Decode process exception. 4. Insufficient memory.            |
3847
3848**Example**
3849
3850```ts
3851import { image } from '@kit.ImageKit';
3852import { rpc } from '@kit.IPCKit';
3853
3854class MySequence implements rpc.Parcelable {
3855  pixel_map: image.PixelMap;
3856  constructor(conPixelMap : image.PixelMap) {
3857    this.pixel_map = conPixelMap;
3858  }
3859  marshalling(messageSequence : rpc.MessageSequence) {
3860    this.pixel_map.marshalling(messageSequence);
3861    console.info('marshalling');
3862    return true;
3863  }
3864  unmarshalling(messageSequence : rpc.MessageSequence) {
3865    image.createPixelMap(new ArrayBuffer(96), {size: { height:4, width: 6}}).then((pixelParcel: image.PixelMap) => {
3866      pixelParcel.unmarshalling(messageSequence).then(async (pixelMap: image.PixelMap) => {
3867        this.pixel_map = pixelMap;
3868        pixelMap.getImageInfo().then((imageInfo: image.ImageInfo) => {
3869          console.info("unmarshalling information h:" + imageInfo.size.height + "w:" + imageInfo.size.width);
3870        })
3871      })
3872    });
3873    return true;
3874  }
3875}
3876async function Marshalling() {
3877  const color: ArrayBuffer = new ArrayBuffer(96);
3878  let bufferArr: Uint8Array = new Uint8Array(color);
3879  for (let i = 0; i < bufferArr.length; i++) {
3880    bufferArr[i] = 0x80;
3881  }
3882  let opts: image.InitializationOptions = {
3883    editable: true,
3884    pixelFormat: image.PixelMapFormat.BGRA_8888,
3885    size: { height: 4, width: 6 },
3886    alphaType: image.AlphaType.UNPREMUL
3887  }
3888  let pixelMap: image.PixelMap | undefined = undefined;
3889  image.createPixelMap(color, opts).then((srcPixelMap: image.PixelMap) => {
3890    pixelMap = srcPixelMap;
3891  })
3892  if (pixelMap != undefined) {
3893    // Implement serialization.
3894    let parcelable: MySequence = new MySequence(pixelMap);
3895    let data: rpc.MessageSequence = rpc.MessageSequence.create();
3896    data.writeParcelable(parcelable);
3897
3898    // Implement deserialization to obtain data through the RPC.
3899    let ret: MySequence = new MySequence(pixelMap);
3900    data.readParcelable(ret);
3901  }
3902}
3903```
3904
3905### unmarshalling<sup>10+</sup>
3906
3907unmarshalling(sequence: rpc.MessageSequence): Promise\<PixelMap>
3908
3909Unmarshals a MessageSequence object to obtain a PixelMap object.
3910To create a PixelMap object in synchronous mode, use [createPixelMapFromParcel](#imagecreatepixelmapfromparcel11).
3911
3912**System capability**: SystemCapability.Multimedia.Image.Core
3913
3914**Parameters**
3915
3916| Name                | Type                                                 | Mandatory| Description                                    |
3917| ---------------------- | ----------------------------------------------------- | ---- | ---------------------------------------- |
3918| sequence               | [rpc.MessageSequence](../apis-ipc-kit/js-apis-rpc.md#messagesequence9) | Yes  | MessageSequence object that stores the PixelMap information.     |
3919
3920**Return value**
3921
3922| Type                            | Description                 |
3923| -------------------------------- | --------------------- |
3924| Promise\<[PixelMap](#pixelmap7)> |Promise used to return the PixelMap object.|
3925
3926**Error codes**
3927
3928For details about the error codes, see [Image Error Codes](errorcode-image.md).
3929
3930| ID| Error Message|
3931| ------- | --------------------------------------------|
3932| 62980115 | Invalid image parameter.              |
3933| 62980097 | IPC error. Possible cause: 1.IPC communication failed. 2. Image upload exception. 3. Decode process exception. 4. Insufficient memory.              |
3934| 62980096 | Operation failed.Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.         |
3935
3936**Example**
3937
3938```ts
3939import { image } from '@kit.ImageKit';
3940import { rpc } from '@kit.IPCKit';
3941
3942class MySequence implements rpc.Parcelable {
3943  pixel_map: image.PixelMap;
3944  constructor(conPixelMap: image.PixelMap) {
3945    this.pixel_map = conPixelMap;
3946  }
3947  marshalling(messageSequence: rpc.MessageSequence) {
3948    this.pixel_map.marshalling(messageSequence);
3949    console.info('marshalling');
3950    return true;
3951  }
3952  unmarshalling(messageSequence: rpc.MessageSequence) {
3953    image.createPixelMap(new ArrayBuffer(96), {size: { height:4, width: 6}}).then((pixelParcel : image.PixelMap) => {
3954      pixelParcel.unmarshalling(messageSequence).then(async (pixelMap : image.PixelMap) => {
3955        this.pixel_map = pixelMap;
3956        pixelMap.getImageInfo().then((imageInfo : image.ImageInfo) => {
3957          console.info("unmarshalling information h:" + imageInfo.size.height + "w:" + imageInfo.size.width);
3958        })
3959      })
3960    });
3961    return true;
3962  }
3963}
3964async function Unmarshalling() {
3965  const color: ArrayBuffer = new ArrayBuffer(96);
3966  let bufferArr: Uint8Array = new Uint8Array(color);
3967  for (let i = 0; i < bufferArr.length; i++) {
3968    bufferArr[i] = 0x80;
3969  }
3970  let opts: image.InitializationOptions = {
3971    editable: true,
3972    pixelFormat: image.PixelMapFormat.BGRA_8888,
3973    size: { height: 4, width: 6 },
3974    alphaType: image.AlphaType.UNPREMUL
3975  }
3976  let pixelMap: image.PixelMap | undefined = undefined;
3977  image.createPixelMap(color, opts).then((srcPixelMap : image.PixelMap) => {
3978    pixelMap = srcPixelMap;
3979  })
3980  if (pixelMap != undefined) {
3981    // Implement serialization.
3982    let parcelable: MySequence = new MySequence(pixelMap);
3983    let data : rpc.MessageSequence = rpc.MessageSequence.create();
3984    data.writeParcelable(parcelable);
3985
3986    // Implement deserialization to obtain data through the RPC.
3987    let ret : MySequence = new MySequence(pixelMap);
3988    data.readParcelable(ret);
3989  }
3990}
3991```
3992
3993### release<sup>7+</sup>
3994
3995release():Promise\<void>
3996
3997Releases this PixelMap object. This API uses a promise to return the result.
3998
3999ArkTS supports memory reclamation. Even if the application does not call **release()**, the memory of the PixelMap object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
4000
4001**Widget capability**: This API can be used in ArkTS widgets since API version 12.
4002
4003**Atomic service API**: This API can be used in atomic services since API version 11.
4004
4005**System capability**: SystemCapability.Multimedia.Image.Core
4006
4007**Return value**
4008
4009| Type          | Description                           |
4010| -------------- | ------------------------------- |
4011| Promise\<void> | Promise that returns no value.|
4012
4013**Example**
4014
4015```ts
4016import { BusinessError } from '@kit.BasicServicesKit';
4017
4018async function Release() {
4019  if (pixelMap != undefined) {
4020    pixelMap.release().then(() => {
4021      console.info('Succeeded in releasing pixelmap object.');
4022    }).catch((error: BusinessError) => {
4023      console.error(`Failed to release pixelmap object. code is ${error.code}, message is ${error.message}`);
4024    })
4025  }
4026}
4027```
4028
4029### release<sup>7+</sup>
4030
4031release(callback: AsyncCallback\<void>): void
4032
4033Releases this PixelMap object. This API uses an asynchronous callback to return the result.
4034
4035ArkTS supports memory reclamation. Even if the application does not call **release()**, the memory of the PixelMap object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
4036
4037**Widget capability**: This API can be used in ArkTS widgets since API version 12.
4038
4039**Atomic service API**: This API can be used in atomic services since API version 11.
4040
4041**System capability**: SystemCapability.Multimedia.Image.Core
4042
4043**Parameters**
4044
4045| Name  | Type                | Mandatory| Description              |
4046| -------- | -------------------- | ---- | ------------------ |
4047| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
4048
4049**Example**
4050
4051```ts
4052import { BusinessError } from '@kit.BasicServicesKit';
4053
4054async function Release() {
4055  if (pixelMap != undefined) {
4056    pixelMap.release((err: BusinessError) => {
4057      if (err) {
4058        console.error(`Failed to release pixelmap object. code is ${err.code}, message is ${err.message}`);
4059        return;
4060      } else {
4061        console.info('Succeeded in releasing pixelmap object.');
4062      }
4063    })
4064  }
4065}
4066```
4067
4068### convertPixelFormat<sup>12+</sup>
4069
4070convertPixelFormat(targetPixelFormat: PixelMapFormat): Promise\<void>
4071
4072Performs a conversion between YUV and RGB formats. Currently, only conversion between NV12/NV21 and RGB888/RGBA8888/RGB565/BGRA8888/RGBAF16 and conversion between YCRCB_P010/YCBCR_P010 and RGBA1010102 are supported.
4073
4074Since API version 18, this API can be used for conversion from ASTC_4x4 to RGBA_8888.
4075
4076> **NOTE**
4077>
4078> Call this API to convert the format from ASTC_4x4 to RGBA_8888 only when you need to access pixels of images in ASTC_4x4 format. The conversion from ASTC_4x4 to RGBA_8888 is slow and is not recommended in other cases.
4079
4080**System capability**: SystemCapability.Multimedia.Image.Core
4081
4082**Parameters**
4083
4084| Name  | Type                | Mandatory| Description              |
4085| -------- | -------------------- | ---- | ------------------ |
4086| targetPixelFormat | [PixelMapFormat](#pixelmapformat7) | Yes  | Target pixel format. Currently, only conversion between NV12/NV21 and RGB888/RGBA8888/RGB565/BGRA8888/RGBAF16, conversion between YCRCB_P010/YCBCR_P010 and RGBA1010102, and conversion from ASTC_4x4 to RGBA_8888 are supported.|
4087
4088**Return value**
4089
4090| Type          | Description                           |
4091| -------------- | ------------------------------- |
4092| Promise\<void> | Promise that returns no value.|
4093
4094**Error codes**
4095
4096For details about the error codes, see [Image Error Codes](errorcode-image.md).
4097
4098| ID| Error Message|
4099| ------- | --------------------------------------------|
4100| 62980111 | The image source data is incomplete. |
4101| 62980115 | Invalid input parameter.              |
4102| 62980178 | Failed to create the pixelmap. |
4103| 62980274 | The conversion failed |
4104| 62980276 | The type to be converted is an unsupported target pixel format|
4105
4106**Example**
4107
4108```ts
4109import { BusinessError } from '@kit.BasicServicesKit';
4110
4111if (pixelMap != undefined) {
4112  // Set the target pixel format to NV12.
4113  let targetPixelFormat = image.PixelMapFormat.NV12;
4114  pixelMap.convertPixelFormat(targetPixelFormat).then(() => {
4115    // The pixelMap is converted to the NV12 format.
4116    console.info('PixelMapFormat convert Succeeded');
4117  }).catch((error: BusinessError) => {
4118    // The pixelMap fails to be converted to the NV12 format.
4119    console.error(`PixelMapFormat convert Failed. code is ${error.code}, message is ${error.message}`);
4120  })
4121}
4122```
4123
4124### setMemoryNameSync<sup>13+</sup>
4125
4126setMemoryNameSync(name: string): void
4127
4128Sets a memory name for this PixelMap.
4129
4130**System capability**: SystemCapability.Multimedia.Image.Core
4131
4132**Parameters**
4133
4134| Name       | Type                            | Mandatory| Description            |
4135| ------------- | -------------------------------- | ---- | ---------------- |
4136| name | string | Yes  | Memory name, which can be set only for a PixelMap with the DMA or ASHMEM memory format. The length ranges from 1 to 31 bits.|
4137
4138**Error codes**
4139
4140For details about the error codes, see [Image Error Codes](errorcode-image.md).
4141
4142| ID| Error Message|
4143| ------- | --------------------------------------------|
4144| 401 | Parameter error. Possible causes: 1.The length of the input parameter is too long. 2.Parameter verification failed. |
4145| 501 | Resource unavailable. |
4146| 62980286 | Memory format not supported. |
4147
4148**Example**
4149
4150```ts
4151import { BusinessError } from '@ohos.base';
4152
4153async function SetMemoryNameSync() {
4154  if (pixelMap != undefined) {
4155    try {
4156      pixelMap.setMemoryNameSync("PixelMapName Test");
4157    } catch(e) {
4158      let error = e as BusinessError;
4159      console.error(`setMemoryNameSync error. code is ${error.code}, message is ${error.message}`);
4160    }
4161  }
4162}
4163```
4164
4165## image.createImageSource
4166
4167createImageSource(uri: string): ImageSource
4168
4169Creates an ImageSource instance based on a given URI.
4170
4171
4172**Atomic service API**: This API can be used in atomic services since API version 11.
4173
4174**System capability**: SystemCapability.Multimedia.Image.ImageSource
4175
4176**Parameters**
4177
4178| Name| Type  | Mandatory| Description                              |
4179| ------ | ------ | ---- | ---------------------------------- |
4180| 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, .heic<sup>12+</sup> (depending on the hardware), [.svg<sup>10+</sup>](#svg-tags), and .ico<sup>11+</sup>.|
4181
4182**Return value**
4183
4184| Type                       | Description                                        |
4185| --------------------------- | -------------------------------------------- |
4186| [ImageSource](#imagesource) | ImageSource instance. If the operation fails, undefined is returned.|
4187
4188**Example**
4189
4190<!--code_no_check-->
4191```ts
4192import { common } from '@kit.AbilityKit';
4193
4194// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
4195let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
4196// 'test.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
4197const path: string = context.filesDir + "/test.jpg";
4198const imageSourceApi: image.ImageSource = image.createImageSource(path);
4199```
4200
4201## image.createImageSource<sup>9+</sup>
4202
4203createImageSource(uri: string, options: SourceOptions): ImageSource
4204
4205Creates an ImageSource instance based on a given URI.
4206
4207**Widget capability**: This API can be used in ArkTS widgets since API version 12.
4208
4209**Atomic service API**: This API can be used in atomic services since API version 11.
4210
4211**System capability**: SystemCapability.Multimedia.Image.ImageSource
4212
4213**Parameters**
4214
4215| Name | Type                           | Mandatory| Description                               |
4216| ------- | ------------------------------- | ---- | ----------------------------------- |
4217| 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, .heic<sup>12+</sup> (depending on the hardware), [.svg<sup>10+</sup>](#svg-tags), and .ico<sup>11+</sup>.|
4218| options | [SourceOptions](#sourceoptions9) | Yes  | Image properties, including the image pixel density, pixel format, and image size.|
4219
4220**Return value**
4221
4222| Type                       | Description                                        |
4223| --------------------------- | -------------------------------------------- |
4224| [ImageSource](#imagesource) | ImageSource instance. If the operation fails, undefined is returned.|
4225
4226**Example**
4227
4228<!--code_no_check-->
4229```ts
4230import { common } from '@kit.AbilityKit';
4231
4232let sourceOptions: image.SourceOptions = { sourceDensity: 120 };
4233// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
4234let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
4235// 'test.png' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
4236const path: string = context.filesDir + "/test.png";
4237let imageSourceApi: image.ImageSource = image.createImageSource(path, sourceOptions);
4238```
4239
4240## image.createImageSource<sup>7+</sup>
4241
4242createImageSource(fd: number): ImageSource
4243
4244Creates an ImageSource instance based on a given file descriptor.
4245
4246**Atomic service API**: This API can be used in atomic services since API version 11.
4247
4248**System capability**: SystemCapability.Multimedia.Image.ImageSource
4249
4250**Parameters**
4251
4252| Name| Type  | Mandatory| Description         |
4253| ------ | ------ | ---- | ------------- |
4254| fd     | number | Yes  | File descriptor.|
4255
4256**Return value**
4257
4258| Type                       | Description                                        |
4259| --------------------------- | -------------------------------------------- |
4260| [ImageSource](#imagesource) | ImageSource instance. If the operation fails, undefined is returned.|
4261
4262**Example**
4263
4264<!--code_no_check-->
4265```ts
4266import { fileIo as fs } from '@kit.CoreFileKit';
4267import { common } from '@kit.AbilityKit';
4268
4269// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
4270let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
4271// 'test.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
4272let filePath: string = context.filesDir + "/test.jpg";
4273let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
4274const imageSourceApi: image.ImageSource = image.createImageSource(file.fd);
4275```
4276
4277## image.createImageSource<sup>9+</sup>
4278
4279createImageSource(fd: number, options: SourceOptions): ImageSource
4280
4281Creates an ImageSource instance based on a given file descriptor.
4282
4283**Widget capability**: This API can be used in ArkTS widgets since API version 12.
4284
4285**Atomic service API**: This API can be used in atomic services since API version 11.
4286
4287**System capability**: SystemCapability.Multimedia.Image.ImageSource
4288
4289**Parameters**
4290
4291| Name | Type                           | Mandatory| Description                               |
4292| ------- | ------------------------------- | ---- | ----------------------------------- |
4293| fd      | number                          | Yes  | File descriptor.                     |
4294| options | [SourceOptions](#sourceoptions9) | Yes  | Image properties, including the image pixel density, pixel format, and image size.|
4295
4296**Return value**
4297
4298| Type                       | Description                                        |
4299| --------------------------- | -------------------------------------------- |
4300| [ImageSource](#imagesource) | ImageSource instance. If the operation fails, undefined is returned.|
4301
4302**Example**
4303
4304<!--code_no_check-->
4305```ts
4306import { fileIo as fs } from '@kit.CoreFileKit';
4307import { common } from '@kit.AbilityKit';
4308
4309let sourceOptions: image.SourceOptions = { sourceDensity: 120 };
4310// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
4311let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
4312// 'test.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
4313const filePath: string = context.filesDir + "/test.jpg";
4314let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
4315const imageSourceApi: image.ImageSource = image.createImageSource(file.fd, sourceOptions);
4316```
4317
4318## image.createImageSource<sup>9+</sup>
4319
4320createImageSource(buf: ArrayBuffer): ImageSource
4321
4322Creates an ImageSource instance based on buffers. The data passed by **buf** must be undecoded. Do not pass the pixel buffer data such as RBGA and YUV. If you want to create a PixelMap based on the pixel buffer data, call [image.createPixelMapSync](#createpixelmapsync12).
4323
4324**Widget capability**: This API can be used in ArkTS widgets since API version 12.
4325
4326**Atomic service API**: This API can be used in atomic services since API version 11.
4327
4328**System capability**: SystemCapability.Multimedia.Image.ImageSource
4329
4330**Parameters**
4331
4332| Name| Type       | Mandatory| Description            |
4333| ------ | ----------- | ---- | ---------------- |
4334| buf    | ArrayBuffer | Yes  | Array of image buffers.|
4335
4336**Return value**
4337
4338| Type                       | Description                                        |
4339| --------------------------- | -------------------------------------------- |
4340| [ImageSource](#imagesource) | ImageSource instance. If the operation fails, undefined is returned.|
4341
4342
4343**Example**
4344
4345```ts
4346const buf: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4.
4347const imageSourceApi: image.ImageSource = image.createImageSource(buf);
4348```
4349
4350## image.createImageSource<sup>9+</sup>
4351
4352createImageSource(buf: ArrayBuffer, options: SourceOptions): ImageSource
4353
4354Creates an ImageSource instance based on buffers. The data passed by **buf** must be undecoded. Do not pass the pixel buffer data such as RBGA and YUV. If you want to create a PixelMap based on the pixel buffer data, call [image.createPixelMapSync](#createpixelmapsync12).
4355
4356**Widget capability**: This API can be used in ArkTS widgets since API version 12.
4357
4358**Atomic service API**: This API can be used in atomic services since API version 11.
4359
4360**System capability**: SystemCapability.Multimedia.Image.ImageSource
4361
4362**Parameters**
4363
4364| Name| Type                            | Mandatory| Description                                |
4365| ------ | -------------------------------- | ---- | ------------------------------------ |
4366| buf    | ArrayBuffer                      | Yes  | Array of image buffers.                    |
4367| options | [SourceOptions](#sourceoptions9) | Yes  | Image properties, including the image pixel density, pixel format, and image size.|
4368
4369**Return value**
4370
4371| Type                       | Description                                        |
4372| --------------------------- | -------------------------------------------- |
4373| [ImageSource](#imagesource) | ImageSource instance. If the operation fails, undefined is returned.|
4374
4375**Example**
4376
4377```ts
4378const data: ArrayBuffer = new ArrayBuffer(112);
4379let sourceOptions: image.SourceOptions = { sourceDensity: 120 };
4380const imageSourceApi: image.ImageSource = image.createImageSource(data, sourceOptions);
4381```
4382
4383## image.createImageSource<sup>11+</sup>
4384
4385createImageSource(rawfile: resourceManager.RawFileDescriptor, options?: SourceOptions): ImageSource
4386
4387Creates an ImageSource instance based on the raw file descriptor of an image resource file.
4388
4389**Atomic service API**: This API can be used in atomic services since API version 11.
4390
4391**System capability**: SystemCapability.Multimedia.Image.ImageSource
4392
4393**Parameters**
4394
4395| Name| Type                            | Mandatory| Description                                |
4396| ------ | -------------------------------- | ---- | ------------------------------------ |
4397| rawfile | [resourceManager.RawFileDescriptor](../apis-localization-kit/js-apis-resource-manager.md#rawfiledescriptor9) | Yes| Raw file descriptor of the image resource file.|
4398| options | [SourceOptions](#sourceoptions9) | No| Image properties, including the image pixel density, pixel format, and image size.|
4399
4400**Return value**
4401
4402| Type                       | Description                                        |
4403| --------------------------- | -------------------------------------------- |
4404| [ImageSource](#imagesource) | ImageSource instance. If the operation fails, undefined is returned.|
4405
4406**Example**
4407
4408<!--code_no_check-->
4409```ts
4410import { resourceManager } from '@kit.LocalizationKit';
4411import { common } from '@kit.AbilityKit';
4412
4413// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
4414let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
4415// Obtain a resource manager.
4416const resourceMgr: resourceManager.ResourceManager = context.resourceManager;
4417// 'test.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
4418resourceMgr.getRawFd('test.jpg').then((rawFileDescriptor: resourceManager.RawFileDescriptor) => {
4419  const imageSourceApi: image.ImageSource = image.createImageSource(rawFileDescriptor);
4420}).catch((error: BusinessError) => {
4421  console.error(`Failed to get RawFileDescriptor.code is ${error.code}, message is ${error.message}`);
4422})
4423```
4424
4425## image.CreateIncrementalSource<sup>9+</sup>
4426
4427CreateIncrementalSource(buf: ArrayBuffer): ImageSource
4428
4429Creates an ImageSource instance in incremental mode based on buffers. Such an instance does not support reading or writing of EXIF information.
4430
4431The ImageSource instance created in incremental mode supports the following capabilities (applicable to synchronous, callback, and promise modes):
4432- Obtaining image information: Call [getImageInfo](#getimageinfo) to obtain image information by index, or call [getImageInfo](#getimageinfo-1) to directly obtain image information.
4433- Obtaining an image property: Call [getImageProperty](#getimageproperty11) to obtain the value of a property with the specified index in an image.
4434- Obtaining image properties: Call [getImageProperties](#getimageproperties12) to obtain the values of properties with the given names in an image.
4435- Updating incremental data: Call [updateData](#updatedata9) to update data.
4436- Creating a PixelMap object: Call [createPixelMap](#createpixelmap7) or [createPixelMap](#createpixelmap7-2) to create a PixelMap based on decoding options, or call [createPixelMap](#createpixelmap7-1) to create a PixelMap based on default parameters.
4437- Releasing an ImageSource instance: Call [release](#release) to release an image source.
4438
4439**System capability**: SystemCapability.Multimedia.Image.ImageSource
4440
4441**Parameters**
4442
4443| Name | Type       | Mandatory| Description     |
4444| ------- | ------------| ---- | ----------|
4445| buf     | ArrayBuffer | Yes  | Incremental data.|
4446
4447**Return value**
4448
4449| Type                       | Description                             |
4450| --------------------------- | --------------------------------- |
4451| [ImageSource](#imagesource) | ImageSource instance. If the operation fails, undefined is returned.|
4452
4453**Example**
4454
4455<!--code_no_check-->
4456```ts
4457import { common } from '@kit.AbilityKit';
4458
4459// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
4460let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
4461let imageArray = context.resourceManager.getMediaContentSync($r('app.media.startIcon')); // Obtain the image resource.
4462// 'app.media.startIcon' is only an example. Replace it with the actual one in use. Otherwise, the imageArray instance fails to be created, and subsequent operations cannot be performed.
4463let splitBuff1 = imageArray.slice(0, imageArray.byteLength / 2);  // Image slice.
4464let splitBuff2 = imageArray.slice(imageArray.byteLength / 2);
4465const imageSourceIncrementalSApi: image.ImageSource = image.CreateIncrementalSource(new ArrayBuffer(imageArray.byteLength));
4466imageSourceIncrementalSApi.updateData(splitBuff1, false, 0, splitBuff1.byteLength).then(() => {
4467  imageSourceIncrementalSApi.updateData(splitBuff2, true, 0, splitBuff2.byteLength).then(() => {
4468    let pixelMap = imageSourceIncrementalSApi.createPixelMapSync();
4469    let imageInfo = pixelMap.getImageInfoSync();
4470    console.info('Succeeded in creating pixelMap');
4471  }).catch((error : BusinessError) => {
4472    console.error(`Failed to updateData error code is ${error.code}, message is ${error.message}`);
4473  })
4474}).catch((error : BusinessError) => {
4475  console.error(`Failed to updateData error code is ${error.code}, message is ${error.message}`);
4476})
4477```
4478
4479## image.CreateIncrementalSource<sup>9+</sup>
4480
4481CreateIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource
4482
4483Creates an ImageSource instance in incremental mode based on buffers. Such an instance does not support reading or writing of EXIF information.
4484
4485The capabilities supported by the ImageSource instance created by this API are the same as those supported by the instance created by [CreateIncrementalSource(buf: ArrayBuffer): ImageSource](#imagecreateincrementalsource9).
4486
4487**System capability**: SystemCapability.Multimedia.Image.ImageSource
4488
4489**Parameters**
4490
4491| Name | Type                           | Mandatory| Description                                |
4492| ------- | ------------------------------- | ---- | ------------------------------------ |
4493| buf     | ArrayBuffer                     | Yes  | Incremental data.                          |
4494| options | [SourceOptions](#sourceoptions9) | No  | Image properties, including the image pixel density, pixel format, and image size.|
4495
4496**Return value**
4497
4498| Type                       | Description                             |
4499| --------------------------- | --------------------------------- |
4500| [ImageSource](#imagesource) | ImageSource instance. If the operation fails, undefined is returned.|
4501
4502**Example**
4503
4504<!--code_no_check-->
4505```ts
4506import { common } from '@kit.AbilityKit';
4507
4508// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
4509let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
4510let imageArray = context.resourceManager.getMediaContentSync($r('app.media.startIcon')) // Obtain the image resource.
4511// 'app.media.startIcon' is only an example. Replace it with the actual one in use. Otherwise, the imageArray instance fails to be created, and subsequent operations cannot be performed.
4512let splitBuff1 = imageArray.slice(0, imageArray.byteLength / 2);  // Image slice.
4513let splitBuff2 = imageArray.slice(imageArray.byteLength / 2);
4514let sourceOptions: image.SourceOptions = { sourceDensity: 120};
4515
4516const imageSourceIncrementalSApi: image.ImageSource = image.CreateIncrementalSource(new ArrayBuffer(imageArray.byteLength), sourceOptions);
4517imageSourceIncrementalSApi.updateData(splitBuff1, false, 0, splitBuff1.byteLength).then(() => {
4518  imageSourceIncrementalSApi.updateData(splitBuff2, true, 0, splitBuff2.byteLength).then(() => {
4519    let pixelMap = imageSourceIncrementalSApi.createPixelMapSync();
4520    let imageInfo = pixelMap.getImageInfoSync();
4521    console.info('Succeeded in creating pixelMap');
4522  }).catch((error : BusinessError) => {
4523    console.error(`Failed to updateData error code is ${error.code}, message is ${error.message}`);
4524  })
4525}).catch((error : BusinessError) => {
4526  console.error(`Failed to updateData error code is ${error.code}, message is ${error.message}`);
4527})
4528```
4529
4530## ImageSource
4531
4532Provides APIs to obtain image information. Before calling any API in ImageSource, you must use [createImageSource](#imagecreateimagesource) to create an ImageSource instance.
4533
4534### Properties
4535
4536**System capability**: SystemCapability.Multimedia.Image.ImageSource
4537
4538| Name            | Type          | Read Only| Optional| Description                                                        |
4539| ---------------- | -------------- | ---- | ---- | ------------------------------------------------------------ |
4540| supportedFormats | Array\<string> | Yes  | No  | Supported formats, including .png, .jpeg, .bmp, .gif, .webp, .dng., and .heic<sup>12+</sup> (depending on the hardware).|
4541
4542### getImageInfo
4543
4544getImageInfo(index: number, callback: AsyncCallback\<ImageInfo>): void
4545
4546Obtains information about an image with the specified index. This API uses an asynchronous callback to return the result.
4547
4548**Widget capability**: This API can be used in ArkTS widgets since API version 12.
4549
4550**Atomic service API**: This API can be used in atomic services since API version 11.
4551
4552**System capability**: SystemCapability.Multimedia.Image.ImageSource
4553
4554**Parameters**
4555
4556| Name  | Type                                  | Mandatory| Description                                    |
4557| -------- | -------------------------------------- | ---- | ---------------------------------------- |
4558| index    | number                                 | Yes  | Index of the image source. The default value is **0**, indicating the first image. If this parameter is set to N, the (N-1)th image is used. For single-frame images, the value is always **0**. For multi-frame images such as animations, the value ranges from 0 to (Number of frames – 1).                  |
4559| callback | AsyncCallback<[ImageInfo](#imageinfo)> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the image information obtained; otherwise, **err** is an error object.|
4560
4561**Example**
4562
4563```ts
4564import { BusinessError } from '@kit.BasicServicesKit';
4565
4566imageSourceApi.getImageInfo(0, (error: BusinessError, imageInfo: image.ImageInfo) => {
4567  if (error) {
4568    console.error(`Failed to obtain the image information.code is ${error.code}, message is ${error.message}`);
4569  } else {
4570    console.info('Succeeded in obtaining the image information.');
4571  }
4572})
4573```
4574
4575### getImageInfo
4576
4577getImageInfo(callback: AsyncCallback\<ImageInfo>): void
4578
4579Obtains information about this image. This API uses an asynchronous callback to return the result.
4580
4581**Widget capability**: This API can be used in ArkTS widgets since API version 12.
4582
4583**Atomic service API**: This API can be used in atomic services since API version 11.
4584
4585**System capability**: SystemCapability.Multimedia.Image.ImageSource
4586
4587**Parameters**
4588
4589| Name  | Type                                  | Mandatory| Description                                    |
4590| -------- | -------------------------------------- | ---- | ---------------------------------------- |
4591| callback | AsyncCallback<[ImageInfo](#imageinfo)> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the image information obtained; otherwise, **err** is an error object.|
4592
4593**Example**
4594
4595```ts
4596import { BusinessError } from '@kit.BasicServicesKit';
4597
4598imageSourceApi.getImageInfo((err: BusinessError, imageInfo: image.ImageInfo) => {
4599  if (err) {
4600    console.error(`Failed to obtain the image information.code is ${err.code}, message is ${err.message}`);
4601  } else {
4602    console.info('Succeeded in obtaining the image information.');
4603  }
4604})
4605```
4606
4607### getImageInfo
4608
4609getImageInfo(index?: number): Promise\<ImageInfo>
4610
4611Obtains information about an image with the specified index. This API uses a promise to return the result.
4612
4613**Widget capability**: This API can be used in ArkTS widgets since API version 12.
4614
4615**Atomic service API**: This API can be used in atomic services since API version 11.
4616
4617**System capability**: SystemCapability.Multimedia.Image.ImageSource
4618
4619**Parameters**
4620
4621| Name| Type  | Mandatory| Description                                 |
4622| ----- | ------ | ---- | ------------------------------------- |
4623| index | number | No  | Index of the image source. The default value is **0**, indicating the first image. If this parameter is set to N, the (N-1)th image is used. For single-frame images, the value is always **0**. For multi-frame images such as animations, the value ranges from 0 to (Number of frames – 1).|
4624
4625**Return value**
4626
4627| Type                            | Description                  |
4628| -------------------------------- | ---------------------- |
4629| Promise<[ImageInfo](#imageinfo)> | Promise used to return the image information.|
4630
4631**Example**
4632
4633```ts
4634import { BusinessError } from '@kit.BasicServicesKit';
4635
4636imageSourceApi.getImageInfo(0)
4637  .then((imageInfo: image.ImageInfo) => {
4638    console.info('Succeeded in obtaining the image information.');
4639  }).catch((error: BusinessError) => {
4640    console.error(`Failed to obtain the image information.code is ${error.code}, message is ${error.message}`);
4641  })
4642```
4643
4644### getImageInfoSync<sup>12+</sup>
4645
4646getImageInfoSync(index?: number): ImageInfo
4647
4648Obtains information about an image with the specified index. This API returns the result synchronously.
4649
4650**System capability**: SystemCapability.Multimedia.Image.ImageSource
4651
4652**Parameters**
4653
4654| Name| Type  | Mandatory| Description                                 |
4655| ----- | ------ | ---- | ------------------------------------- |
4656| index | number | No  | Index of the image source. The default value is **0**, indicating the first image. If this parameter is set to N, the (N-1)th image is used. For single-frame images, the value is always **0**. For multi-frame images such as animations, the value ranges from 0 to (Number of frames – 1).|
4657
4658**Return value**
4659
4660| Type                            | Description                  |
4661| -------------------------------- | ---------------------- |
4662| [ImageInfo](#imageinfo) | Image information.|
4663
4664**Example**
4665
4666<!--code_no_check-->
4667```ts
4668import { common } from '@kit.AbilityKit';
4669import { image } from '@kit.ImageKit';
4670
4671// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
4672let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
4673// 'test.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
4674let filePath: string = context.filesDir + "/test.jpg";
4675let imageSource = image.createImageSource(filePath);
4676let imageInfo = imageSource.getImageInfoSync(0);
4677if (imageInfo == undefined) {
4678  console.error('Failed to obtain the image information.');
4679} else {
4680  console.info('Succeeded in obtaining the image information.');
4681  console.info('imageInfo.size.height:' + imageInfo.size.height);
4682  console.info('imageInfo.size.width:' + imageInfo.size.width);
4683}
4684```
4685
4686### getImageProperty<sup>11+</sup>
4687
4688getImageProperty(key:PropertyKey, options?: ImagePropertyOptions): Promise\<string>
4689
4690Obtains the value of a property with the specified index in this image. This API uses a promise to return the result. This API applies only to images that are in JPEG, PNG, or HEIF<sup>12+</sup> (depending on the hardware) format and contain the EXIF information. You can use the **supportedFormats** property to check whether the EXIF read/write operation for images in HEIF format is supported.
4691
4692**System capability**: SystemCapability.Multimedia.Image.ImageSource
4693
4694**Parameters**
4695
4696| Name | Type                                                | Mandatory| Description                                |
4697| ------- | ---------------------------------------------------- | ---- | ------------------------------------ |
4698| key     | [PropertyKey](#propertykey7)                                               | Yes  | Name of the property.                        |
4699| options | [ImagePropertyOptions](#imagepropertyoptions11) | No  | Image properties, including the image index and default property value.|
4700
4701**Return value**
4702
4703| Type            | Description                                                             |
4704| ---------------- | ----------------------------------------------------------------- |
4705| Promise\<string> | Promise used to return the property value. If the operation fails, the default value is returned.|
4706
4707**Error codes**
4708
4709For details about the error codes, see [Image Error Codes](errorcode-image.md).
4710
4711| ID| Error Message|
4712| ------- | --------------------------------------------|
4713| 401  | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types;3.Parameter verification failed;              |
4714| 62980096 | Operation failed.Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.             |
4715| 62980103 | The image data is not supported.         |
4716| 62980110 | The image source data is incorrect.      |
4717| 62980111 | The image source data is incomplete. |
4718| 62980112 | The image format does not match.       |
4719| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted.            |
4720| 62980115 | Invalid image parameter.      |
4721| 62980116| Failed to decode the image.            |
4722| 62980118 | Failed to create the image plugin.   |
4723| 62980122 | Failed to decode the image header.   |
4724| 62980123| The image does not support EXIF decoding. |
4725| 62980135| The EXIF value is invalid.             |
4726
4727**Example**
4728
4729```ts
4730import { BusinessError } from '@kit.BasicServicesKit';
4731
4732let options: image.ImagePropertyOptions = { index: 0, defaultValue: '9999' }
4733imageSourceApi.getImageProperty(image.PropertyKey.BITS_PER_SAMPLE, options)
4734.then((data: string) => {
4735  console.info('Succeeded in getting the value of the specified attribute key of the image.');
4736}).catch((error: BusinessError) => {
4737  console.error('Failed to get the value of the specified attribute key of the image.');
4738})
4739```
4740
4741### getImageProperty<sup>(deprecated)</sup>
4742
4743getImageProperty(key:string, options?: GetImagePropertyOptions): Promise\<string>
4744
4745Obtains the value of a property with the specified index in this image. This API uses a promise to return the result. This API applies only to images that are in JPEG, PNG, or HEIF<sup>12+</sup> (depending on the hardware) format and contain the EXIF information. You can use the **supportedFormats** property to check whether the EXIF read/write operation for images in HEIF format is supported.
4746
4747> **NOTE**
4748>
4749> This API is deprecated since API version 11. You are advised to use [getImageProperty](#getimageproperty11).
4750
4751**System capability**: SystemCapability.Multimedia.Image.ImageSource
4752
4753**Parameters**
4754
4755| Name | Type                                                | Mandatory| Description                                |
4756| ------- | ---------------------------------------------------- | ---- | ------------------------------------ |
4757| key     | string                                               | Yes  | Name of the property.                        |
4758| options | [GetImagePropertyOptions](#getimagepropertyoptionsdeprecated) | No  | Image properties, including the image index and default property value.|
4759
4760**Return value**
4761
4762| Type            | Description                                                             |
4763| ---------------- | ----------------------------------------------------------------- |
4764| Promise\<string> | Promise used to return the property value. If the operation fails, the default value is returned.|
4765
4766**Example**
4767
4768```ts
4769import { BusinessError } from '@kit.BasicServicesKit';
4770
4771imageSourceApi.getImageProperty("BitsPerSample")
4772  .then((data: string) => {
4773    console.info('Succeeded in getting the value of the specified attribute key of the image.');
4774  }).catch((error: BusinessError) => {
4775    console.error('Failed to get the value of the specified attribute key of the image.');
4776  })
4777```
4778
4779### getImageProperty<sup>(deprecated)</sup>
4780
4781getImageProperty(key:string, callback: AsyncCallback\<string>): void
4782
4783Obtains the value of a property with the specified index in this image. This API uses an asynchronous callback to return the result. This API applies only to images that are in JPEG, PNG, or HEIF<sup>12+</sup> (depending on the hardware) format and contain the EXIF information. You can use the **supportedFormats** property to check whether the EXIF read/write operation for images in HEIF format is supported.
4784
4785> **NOTE**
4786>
4787> This API is deprecated since API version 11. You are advised to use [getImageProperty](#getimageproperty11).
4788
4789**System capability**: SystemCapability.Multimedia.Image.ImageSource
4790
4791**Parameters**
4792
4793| Name  | Type                  | Mandatory| Description                                                        |
4794| -------- | ---------------------- | ---- | ------------------------------------------------------------ |
4795| key      | string                 | Yes  | Name of the property.                                                |
4796| callback | AsyncCallback\<string> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the property value obtained; otherwise, **err** is an error object.|
4797
4798**Example**
4799
4800```ts
4801import { BusinessError } from '@kit.BasicServicesKit';
4802
4803imageSourceApi.getImageProperty("BitsPerSample", (error: BusinessError, data: string) => {
4804  if (error) {
4805    console.error('Failed to get the value of the specified attribute key of the image.');
4806  } else {
4807    console.info('Succeeded in getting the value of the specified attribute key of the image.');
4808  }
4809})
4810```
4811
4812### getImageProperty<sup>(deprecated)</sup>
4813
4814getImageProperty(key:string, options: GetImagePropertyOptions, callback: AsyncCallback\<string>): void
4815
4816Obtains the value of a property in this image. This API uses an asynchronous callback to return the result. This API applies only to images that are in JPEG, PNG, or HEIF<sup>12+</sup> (depending on the hardware) format and contain the EXIF information. You can use the **supportedFormats** property to check whether the EXIF read/write operation for images in HEIF format is supported.
4817
4818> **NOTE**
4819>
4820> This API is deprecated since API version 11. You are advised to use [getImageProperty](#getimageproperty11).
4821
4822**System capability**: SystemCapability.Multimedia.Image.ImageSource
4823
4824**Parameters**
4825
4826| Name  | Type                                                | Mandatory| Description                                                         |
4827| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------- |
4828| key      | string                                               | Yes  | Name of the property.                                                 |
4829| options  | [GetImagePropertyOptions](#getimagepropertyoptionsdeprecated) | Yes  | Image properties, including the image index and default property value.                         |
4830| callback | AsyncCallback\<string>                               | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the property value obtained; otherwise, **err** is an error object.|
4831
4832**Example**
4833
4834```ts
4835import { BusinessError } from '@kit.BasicServicesKit';
4836
4837let property: image.GetImagePropertyOptions = { index: 0, defaultValue: '9999' }
4838imageSourceApi.getImageProperty("BitsPerSample", property, (error: BusinessError, data: string) => {
4839  if (error) {
4840    console.error('Failed to get the value of the specified attribute key of the image.');
4841  } else {
4842    console.info('Succeeded in getting the value of the specified attribute key of the image.');
4843  }
4844})
4845```
4846
4847### getImageProperties<sup>12+</sup>
4848
4849getImageProperties(key: Array&#60;PropertyKey&#62;): Promise<Record<PropertyKey, string|null>>
4850
4851Obtains the values of properties with the given names in this image. This API uses a promise to return the result. This API applies only to images that are in JPEG, PNG, or HEIF (depending on the hardware) format and contain the EXIF information. You can use the **supportedFormats** property to check whether the EXIF read/write operation for images in HEIF format is supported.
4852
4853**System capability**: SystemCapability.Multimedia.Image.ImageSource
4854
4855**Parameters**
4856
4857| Name | Type                                                | Mandatory| Description                                |
4858| ------- | ---------------------------------------------------- | ---- | ------------------------------------ |
4859| key     | Array\<[PropertyKey](#propertykey7)>                                 | Yes  | Array of properties names.                        |
4860
4861**Return value**
4862
4863| Type            | Description                                                             |
4864| ---------------- | ----------------------------------------------------------------- |
4865| Promise\<Record<[PropertyKey](#propertykey7), string \| null>> | Promise used to return the property values. If the operation fails, **null** is returned.|
4866
4867**Error codes**
4868
4869For details about the error codes, see [Image Error Codes](errorcode-image.md).
4870
4871| ID| Error Message|
4872| ------- | --------------------------------------------|
4873| 401  | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types;3.Parameter verification failed;     |
4874| 62980096| Operation failed.Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.             |
4875| 62980110| The image source data is incorrect.            |
4876| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted.            |
4877| 62980116| Failed to decode the image.            |
4878
4879**Example**
4880
4881```ts
4882import { image } from '@kit.ImageKit';
4883import { BusinessError } from '@kit.BasicServicesKit';
4884
4885let key = [image.PropertyKey.IMAGE_WIDTH, image.PropertyKey.IMAGE_LENGTH];
4886imageSourceApi.getImageProperties(key).then((data) => {
4887  console.info(JSON.stringify(data));
4888}).catch((err: BusinessError) => {
4889  console.error(JSON.stringify(err));
4890});
4891```
4892
4893### getImagePropertySync<sup>20+</sup>
4894
4895getImagePropertySync(key:PropertyKey): string
4896
4897Obtains the value of a specified EXIF property. This API returns the property value in a string.
4898
4899>**NOTE**
4900>
4901> This API applies only to images that are in JPEG, PNG, or HEIF (depending on the hardware) format and contain the EXIF information.
4902>
4903> EXIF information is metadata of the image, including shooting time, camera model, aperture, focal length, and ISO.
4904
4905
4906**System capability**: SystemCapability.Multimedia.Image.ImageSource
4907
4908**Parameters**
4909
4910| Name | Type                                                | Mandatory| Description                                |
4911| ------- | ---------------------------------------------------- | ---- | ------------------------------------ |
4912| key     | [PropertyKey](#propertykey7)                                               | Yes  | Name of the property.                        |
4913
4914**Return value**
4915
4916| Type            | Description                                                             |
4917| ---------------- | ----------------------------------------------------------------- |
4918| string | Value of the specified EXIF property. If retrieval fails, the default value of the property is returned. For details about the meaning of each data value, see [PropertyKey](#propertykey7).|
4919
4920**Error codes**
4921
4922For details about the error codes, see [Image Error Codes](errorcode-image.md).
4923| ID| Error Message|
4924| ------- | --------------------------------------------|
4925| 7700101  | Bad source. e.g.,1. Image has invalid width or height. 2. Image source incomplete. 3. Read image data failed. 4. Codec create failed.|
4926| 7700102 | Unsupported MIME type.|
4927| 7700202 | Unsupported metadata. For example, key is not supported.|
4928
4929**Example**
4930
4931<!--code_no_check-->
4932```ts
4933import { image } from '@kit.ImageKit';
4934import { common } from '@kit.AbilityKit';
4935
4936// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
4937let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
4938let resourceMgr = context.resourceManager;
4939if (resourceMgr == null) {
4940  return;
4941}
4942let fd = resourceMgr.getRawFdSync("example.jpg");
4943
4944const imageSourceApi = image.createImageSource(fd);
4945console.info("getImagePropertySync");
4946let bits_per_sample = imageSourceApi.getImagePropertySync(image.PropertyKey.BITS_PER_SAMPLE);
4947console.info("bits_per_sample : " + bits_per_sample);
4948```
4949
4950### modifyImageProperty<sup>11+</sup>
4951
4952modifyImageProperty(key: PropertyKey, value: string): Promise\<void>
4953
4954Modifies the value of a property in this image. This API uses a promise to return the result. This API applies only to images that are in JPEG, PNG, or HEIF<sup>12+</sup> (depending on the hardware) format and contain the EXIF information. You can use the **supportedFormats** property to check whether the EXIF read/write operation for images in HEIF format is supported.
4955
4956> **NOTE**
4957>
4958> The property byte length is changed when the **modifyImageProperty** API is called to modify the value of a property. Currently, you can call the API in an ImageSource instance created based on a file descriptor or path, but not an ImageSource instance created based on buffers.
4959
4960**System capability**: SystemCapability.Multimedia.Image.ImageSource
4961
4962**Parameters**
4963
4964| Name | Type  | Mandatory| Description        |
4965| ------- | ------ | ---- | ------------ |
4966| key     | [PropertyKey](#propertykey7)   | Yes  | Name of the property.|
4967| value   | string | Yes  | New value of the property.    |
4968
4969**Return value**
4970
4971| Type          | Description                       |
4972| -------------- | --------------------------- |
4973| Promise\<void> | Promise that returns no value.|
4974
4975**Error codes**
4976
4977For details about the error codes, see [Image Error Codes](errorcode-image.md).
4978
4979| ID| Error Message|
4980| ------- | --------------------------------------------|
4981| 401  | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types;    |
4982| 62980123| The image does not support EXIF decoding.             |
4983| 62980133| The EXIF data is out of range.             |
4984| 62980135| The EXIF value is invalid.             |
4985| 62980146| The EXIF data failed to be written to the file.        |
4986
4987**Example**
4988
4989```ts
4990import { BusinessError } from '@kit.BasicServicesKit';
4991
4992imageSourceApi.modifyImageProperty(image.PropertyKey.IMAGE_WIDTH, "120").then(() => {
4993  imageSourceApi.getImageProperty(image.PropertyKey.IMAGE_WIDTH).then((width: string) => {
4994    console.info(`ImageWidth is :${width}`);
4995  }).catch((error: BusinessError) => {
4996    console.error('Failed to get the Image Width.');
4997  })
4998}).catch((error: BusinessError) => {
4999  console.error('Failed to modify the Image Width');
5000})
5001```
5002
5003### modifyImageProperty<sup>(deprecated)</sup>
5004
5005modifyImageProperty(key: string, value: string): Promise\<void>
5006
5007Modifies the value of a property in this image. This API uses a promise to return the result. This API applies only to images that are in JPEG, PNG, or HEIF<sup>12+</sup> (depending on the hardware) format and contain the EXIF information. You can use the **supportedFormats** property to check whether the EXIF read/write operation for images in HEIF format is supported.
5008
5009> **NOTE**
5010>
5011> The property byte length is changed when the **modifyImageProperty** API is called to modify the value of a property. Currently, you can call the API in an ImageSource instance created based on a file descriptor or path, but not an ImageSource instance created based on buffers.
5012>
5013> This API is deprecated since API version 11. You are advised to use [modifyImageProperty](#modifyimageproperty11).
5014
5015**System capability**: SystemCapability.Multimedia.Image.ImageSource
5016
5017**Parameters**
5018
5019| Name | Type  | Mandatory| Description        |
5020| ------- | ------ | ---- | ------------ |
5021| key     | string | Yes  | Name of the property.|
5022| value   | string | Yes  | New value of the property.    |
5023
5024**Return value**
5025
5026| Type          | Description                       |
5027| -------------- | --------------------------- |
5028| Promise\<void> |  Promise that returns no value.|
5029
5030**Example**
5031
5032```ts
5033import { BusinessError } from '@kit.BasicServicesKit';
5034
5035imageSourceApi.modifyImageProperty("ImageWidth", "120").then(() => {
5036  imageSourceApi.getImageProperty("ImageWidth").then((width: string) => {
5037    console.info(`ImageWidth is :${width}`);
5038  }).catch((error: BusinessError) => {
5039    console.error('Failed to get the Image Width.');
5040  })
5041}).catch((error: BusinessError) => {
5042  console.error('Failed to modify the Image Width');
5043})
5044```
5045
5046### modifyImageProperty<sup>(deprecated)</sup>
5047
5048modifyImageProperty(key: string, value: string, callback: AsyncCallback\<void>): void
5049
5050Modifies the value of a property in this image. This API uses an asynchronous callback to return the result. This API applies only to images that are in JPEG, PNG, or HEIF<sup>12+</sup> (depending on the hardware) format and contain the EXIF information. You can use the **supportedFormats** property to check whether the EXIF read/write operation for images in HEIF format is supported.
5051
5052> **NOTE**
5053>
5054> The property byte length is changed when the **modifyImageProperty** API is called to modify the value of a property. Currently, you can call the API in an ImageSource instance created based on a file descriptor or path, but not an ImageSource instance created based on buffers.
5055>
5056>This API is deprecated since API version 11. You are advised to use [modifyImageProperty](#modifyimageproperty11).
5057
5058**System capability**: SystemCapability.Multimedia.Image.ImageSource
5059
5060**Parameters**
5061
5062| Name  | Type               | Mandatory| Description                          |
5063| -------- | ------------------- | ---- | ------------------------------ |
5064| key      | string              | Yes  | Name of the property.                  |
5065| value    | string              | Yes  | New value of the property.                      |
5066| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
5067
5068**Example**
5069
5070```ts
5071import { BusinessError } from '@kit.BasicServicesKit';
5072
5073imageSourceApi.modifyImageProperty("ImageWidth", "120", (err: BusinessError) => {
5074  if (err) {
5075    console.error(`Failed to modify the Image Width.code is ${err.code}, message is ${err.message}`);
5076  } else {
5077    console.info('Succeeded in modifying the Image Width.');
5078  }
5079})
5080```
5081
5082### modifyImageProperties<sup>12+</sup>
5083
5084modifyImageProperties(records: Record<PropertyKey, string|null>): Promise\<void>
5085
5086Modifies the values of properties in this image. This API uses a promise to return the result. This API applies only to images that are in JPEG, PNG, or HEIF (depending on the hardware) format and contain the EXIF information. You can use the **supportedFormats** property to check whether the EXIF read/write operation for images in HEIF format is supported.
5087
5088> **NOTE**
5089>
5090> The property byte length is changed when the **modifyImageProperties** API is called to modify the values of properties. Currently, you can call the API in an ImageSource instance created based on a file descriptor or path, but not an ImageSource instance created based on buffers.
5091>
5092
5093**System capability**: SystemCapability.Multimedia.Image.ImageSource
5094
5095**Parameters**
5096
5097| Name | Type  | Mandatory| Description        |
5098| ------- | ------ | ---- | ------------ |
5099| records     | Record<[PropertyKey](#propertykey7), string \| null>   | Yes  | Array of property names and property values.|
5100
5101**Return value**
5102
5103| Type          | Description                       |
5104| -------------- | --------------------------- |
5105| Promise\<void> |  Promise that returns no value.|
5106
5107**Error codes**
5108
5109For details about the error codes, see [Image Error Codes](errorcode-image.md).
5110
5111| ID| Error Message|
5112| ------- | --------------------------------------------|
5113| 401  | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types;3.Parameter verification failed;      |
5114| 62980123| The image does not support EXIF decoding.             |
5115| 62980133| The EXIF data is out of range.             |
5116| 62980135| The EXIF value is invalid.             |
5117| 62980146| The EXIF data failed to be written to the file.             |
5118
5119**Example**
5120
5121```ts
5122import { image } from '@kit.ImageKit';
5123import { BusinessError } from '@kit.BasicServicesKit';
5124
5125let keyValues: Record<PropertyKey, string|null> = {
5126    [image.PropertyKey.IMAGE_WIDTH] : "1024",
5127    [image.PropertyKey.IMAGE_LENGTH] : "1024"
5128};
5129let checkKey = [image.PropertyKey.IMAGE_WIDTH, image.PropertyKey.IMAGE_LENGTH];
5130imageSourceApi.modifyImageProperties(keyValues).then(() => {
5131  imageSourceApi.getImageProperties(checkKey).then((data) => {
5132    console.info(JSON.stringify(data));
5133  }).catch((err: BusinessError) => {
5134    console.error(JSON.stringify(err));
5135  });
5136}).catch((err: BusinessError) => {
5137  console.error(JSON.stringify(err));
5138});
5139```
5140
5141### updateData<sup>9+</sup>
5142
5143updateData(buf: ArrayBuffer, isFinished: boolean, offset: number, length: number): Promise\<void>
5144
5145Updates incremental data. This API uses a promise to return the result.
5146
5147**System capability**: SystemCapability.Multimedia.Image.ImageSource
5148
5149**Parameters**
5150
5151| Name    | Type       | Mandatory| Description        |
5152| ---------- | ----------- | ---- | ------------ |
5153| buf        | ArrayBuffer         | Yes  | Buffer for storing the incremental data.          |
5154| isFinished | boolean             | Yes  | Whether data update is complete. The value **true** means that the data update is complete and the last segment of data is stored in the buffer. The value **false** means that the data update is still in progress.|
5155| offset      | number              | Yes  | Offset of the data in the buffer, measured from the start of the entire image file, in bytes.            |
5156| length     | number              | Yes  | Length of the buffer, in bytes.           |
5157
5158**Return value**
5159
5160| Type          | Description                      |
5161| -------------- | -------------------------- |
5162| Promise\<void> | Promise that returns no value.|
5163
5164**Example**
5165
5166```ts
5167import { BusinessError } from '@kit.BasicServicesKit';
5168
5169const array: ArrayBuffer = new ArrayBuffer(100);
5170imageSourceApi.updateData(array, false, 0, 10).then(() => {
5171  console.info('Succeeded in updating data.');
5172}).catch((err: BusinessError) => {
5173  console.error(`Failed to update data.code is ${err.code},message is ${err.message}`);
5174})
5175```
5176
5177
5178### updateData<sup>9+</sup>
5179
5180updateData(buf: ArrayBuffer, isFinished: boolean, offset: number, length: number, callback: AsyncCallback\<void>): void
5181
5182Updates incremental data. This API uses an asynchronous callback to return the result.
5183
5184**System capability**: SystemCapability.Multimedia.Image.ImageSource
5185
5186**Parameters**
5187
5188| Name    | Type               | Mandatory| Description                |
5189| ---------- | ------------------- | ---- | -------------------- |
5190| buf        | ArrayBuffer         | Yes  | Buffer for storing the incremental data.          |
5191| isFinished | boolean             | Yes  | Whether data update is complete. The value **true** means that the data update is complete and the last segment of data is stored in the buffer. The value **false** means that the data update is still in progress.|
5192| offset      | number              | Yes  | Offset of the data in the buffer, measured from the start of the entire image file, in bytes.            |
5193| length     | number              | Yes  | Length of the buffer, in bytes.           |
5194| callback   | AsyncCallback\<void> | Yes  |  Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
5195
5196**Example**
5197
5198```ts
5199import { BusinessError } from '@kit.BasicServicesKit';
5200
5201const array: ArrayBuffer = new ArrayBuffer(100);
5202imageSourceApi.updateData(array, false, 0, 10, (err: BusinessError) => {
5203  if (err) {
5204    console.error(`Failed to update data.code is ${err.code},message is ${err.message}`);
5205  } else {
5206    console.info('Succeeded in updating data.');
5207  }
5208})
5209```
5210
5211### createPicture<sup>13+</sup>
5212
5213createPicture(options?: DecodingOptionsForPicture): Promise\<Picture>
5214
5215Creates a Picture object based on decoding options. This API uses a promise to return the result.
5216
5217**System capability**: SystemCapability.Multimedia.Image.ImageSource
5218
5219**Parameters**
5220
5221| Name | Type                                                  | Mandatory| Description      |
5222| ------- | ------------------------------------------------------ | ---- | ---------- |
5223| options | [DecodingOptionsForPicture](#decodingoptionsforpicture13) | No  | Decoding options.|
5224
5225**Return value**
5226
5227| Type                        | Description                      |
5228| ---------------------------- | -------------------------- |
5229| Promise\<[Picture](#picture13)> | Promise used to return the Picture object.|
5230
5231**Error codes**
5232
5233For details about the error codes, see [Image Error Codes](errorcode-image.md).
5234
5235| ID| Error Message                                                    |
5236| -------- | ------------------------------------------------------------ |
5237| 401      | Parameter error.Possible causes: 1.Mandatory parameters are left unspecified.2.Incorrect parameter types; 3.Parameter verification failed. |
5238| 7700301  | Failed to decode image.                                      |
5239
5240**Example**
5241
5242```ts
5243import { image } from '@kit.ImageKit';
5244
5245async function CreatePicture() {
5246  let options: image.DecodingOptionsForPicture = {
5247    desiredAuxiliaryPictures: [image.AuxiliaryPictureType.GAINMAP] // GAINMAP indicates the type of the auxiliary picture to be decoded.
5248  };
5249  let pictureObj: image.Picture = await imageSourceApi.createPicture(options);
5250  if (pictureObj != null) {
5251    console.info('Create picture succeeded');
5252  } else {
5253    console.error('Create picture failed');
5254  }
5255}
5256```
5257
5258### createPixelMap<sup>7+</sup>
5259
5260createPixelMap(options?: DecodingOptions): Promise\<PixelMap>
5261
5262Creates a PixelMap object based on decoding options. This API uses a promise to return the result.
5263
5264Starting from API version 15, you are advised to use [createPixelMapUsingAllocator](#createpixelmapusingallocator15). This API can be used to specify the memory type [AllocatorType](#allocatortype15) of the output PixelMap. For details, see [Allocating Memory for Image Decoding (ArkTS)](../../media/image/image-allocator-type.md).
5265
5266**Widget capability**: This API can be used in ArkTS widgets since API version 12.
5267
5268**Atomic service API**: This API can be used in atomic services since API version 11.
5269
5270**System capability**: SystemCapability.Multimedia.Image.ImageSource
5271
5272**Parameters**
5273
5274| Name | Type                                | Mandatory| Description      |
5275| ------- | ------------------------------------ | ---- | ---------- |
5276| options | [DecodingOptions](#decodingoptions7) | No  | Decoding options.|
5277
5278**Return value**
5279
5280| Type                            | Description                 |
5281| -------------------------------- | --------------------- |
5282| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the PixelMap object.|
5283
5284**Example**
5285
5286```ts
5287import { BusinessError } from '@kit.BasicServicesKit';
5288
5289imageSourceApi.createPixelMap().then((pixelMap: image.PixelMap) => {
5290  console.info('Succeeded in creating pixelMap object through image decoding parameters.');
5291}).catch((error: BusinessError) => {
5292  console.error('Failed to create pixelMap object through image decoding parameters.');
5293})
5294```
5295
5296### createPixelMap<sup>7+</sup>
5297
5298createPixelMap(callback: AsyncCallback\<PixelMap>): void
5299
5300Creates a PixelMap object based on the default parameters. This API uses an asynchronous callback to return the result.
5301
5302Starting from API version 15, you are advised to use [createPixelMapUsingAllocator](#createpixelmapusingallocator15). This API can be used to specify the memory type [AllocatorType](#allocatortype15) of the output PixelMap. For details, see [Allocating Memory for Image Decoding (ArkTS)](../../media/image/image-allocator-type.md).
5303
5304**Widget capability**: This API can be used in ArkTS widgets since API version 12.
5305
5306**Atomic service API**: This API can be used in atomic services since API version 11.
5307
5308**System capability**: SystemCapability.Multimedia.Image.ImageSource
5309
5310**Parameters**
5311
5312| Name    | Type                                 | Mandatory| Description                      |
5313| -------- | ------------------------------------- | ---- | -------------------------- |
5314| callback | AsyncCallback<[PixelMap](#pixelmap7)> | Yes  | Callback used to return the result. If the operation is successful, **err** is undefined and **data** is the PixelMap object obtained; otherwise, **err** is an error object.|
5315
5316**Example**
5317
5318```ts
5319import { BusinessError } from '@kit.BasicServicesKit';
5320
5321imageSourceApi.createPixelMap((err: BusinessError, pixelMap: image.PixelMap) => {
5322  if (err) {
5323    console.error(`Failed to create pixelMap.code is ${err.code},message is ${err.message}`);
5324  } else {
5325    console.info('Succeeded in creating pixelMap object.');
5326  }
5327})
5328```
5329
5330### createPixelMap<sup>7+</sup>
5331
5332createPixelMap(options: DecodingOptions, callback: AsyncCallback\<PixelMap>): void
5333
5334Creates a PixelMap object based on decoding options. This API uses an asynchronous callback to return the result.
5335
5336Starting from API version 15, you are advised to use [createPixelMapUsingAllocator](#createpixelmapusingallocator15). This API can be used to specify the memory type [AllocatorType](#allocatortype15) of the output PixelMap. For details, see [Allocating Memory for Image Decoding (ArkTS)](../../media/image/image-allocator-type.md).
5337
5338**Widget capability**: This API can be used in ArkTS widgets since API version 12.
5339
5340**Atomic service API**: This API can be used in atomic services since API version 11.
5341
5342**System capability**: SystemCapability.Multimedia.Image.ImageSource
5343
5344**Parameters**
5345
5346| Name  | Type                                 | Mandatory| Description                      |
5347| -------- | ------------------------------------- | ---- | -------------------------- |
5348| options  | [DecodingOptions](#decodingoptions7)  | Yes  | Decoding options.                |
5349| callback | AsyncCallback<[PixelMap](#pixelmap7)> | Yes  | Callback used to return the result. If the operation is successful, **err** is undefined and **data** is the PixelMap object obtained; otherwise, **err** is an error object.|
5350
5351**Example**
5352
5353```ts
5354import { BusinessError } from '@kit.BasicServicesKit';
5355
5356let decodingOptions: image.DecodingOptions = {
5357  sampleSize: 1,
5358  editable: true,
5359  desiredSize: { width: 1, height: 2 },
5360  rotate: 10,
5361  desiredPixelFormat: image.PixelMapFormat.RGBA_8888,
5362  desiredRegion: { size: { width: 1, height: 2 }, x: 0, y: 0 },
5363  cropAndScaleStrategy: image.CropAndScaleStrategy.CROP_FIRST,
5364  index: 0
5365};
5366imageSourceApi.createPixelMap(decodingOptions, (err: BusinessError, pixelMap: image.PixelMap) => {
5367  if (err) {
5368    console.error(`Failed to create pixelMap.code is ${err.code},message is ${err.message}`);
5369  } else {
5370    console.info('Succeeded in creating pixelMap object.');
5371  }
5372})
5373```
5374
5375### createPixelMapSync<sup>12+</sup>
5376
5377createPixelMapSync(options?: DecodingOptions): PixelMap
5378
5379Creates a PixelMap object based on decoding options. This API returns the result synchronously.
5380
5381Starting from API version 15, you are advised to use [createPixelMapUsingAllocatorSync](#createpixelmapusingallocatorsync15). This API can be used to specify the memory type [AllocatorType](#allocatortype15) of the output PixelMap. For details, see [Allocating Memory for Image Decoding (ArkTS)](../../media/image/image-allocator-type.md).
5382
5383**System capability**: SystemCapability.Multimedia.Image.ImageSource
5384
5385**Parameters**
5386
5387| Name  | Type                                 | Mandatory| Description                      |
5388| -------- | ------------------------------------- | ---- | -------------------------- |
5389| options  | [DecodingOptions](#decodingoptions7)  | No  | Decoding options.                |
5390
5391**Return value**
5392
5393| Type                            | Description                 |
5394| -------------------------------- | --------------------- |
5395| [PixelMap](#pixelmap7) | PixelMap object.|
5396
5397**Example**
5398
5399<!--code_no_check-->
5400```ts
5401import { common } from '@kit.AbilityKit';
5402import { image } from '@kit.ImageKit';
5403
5404// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
5405let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
5406// 'test.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
5407let filePath: string = context.filesDir + "/test.jpg";
5408let imageSource = image.createImageSource(filePath);
5409let decodingOptions: image.DecodingOptions = {
5410  sampleSize: 1,
5411  editable: true,
5412  desiredSize: { width: 1, height: 2 },
5413  rotate: 10,
5414  desiredPixelFormat: image.PixelMapFormat.RGBA_8888,
5415  desiredRegion: { size: { width: 1, height: 2 }, x: 0, y: 0 },
5416  cropAndScaleStrategy: image.CropAndScaleStrategy.CROP_FIRST,
5417  index: 0
5418};
5419let pixelmap = imageSource.createPixelMapSync(decodingOptions);
5420if (pixelmap != undefined) {
5421  console.info('Succeeded in creating pixelMap object.');
5422} else {
5423  console.error('Failed to create pixelMap.');
5424}
5425```
5426
5427### createPixelMapList<sup>10+</sup>
5428
5429createPixelMapList(options?: DecodingOptions): Promise<Array\<PixelMap>>
5430
5431Creates an array of PixelMap objects based on decoding options. This API uses a promise to return the result. For dynamic images such as GIF and WebP images, this API returns the data of each frame of the image. For static images, this API returns the data of the unique frame of the image.
5432
5433> **NOTE**
5434>
5435> This function decodes all frames at once. If the number of frames is high or the size of individual frames is large, it can lead to significant memory usage. In these cases, you are advised to use the **Image** component for displaying animations. The **Image** component decodes frames one by one, which uses less memory than this function.
5436
5437**System capability**: SystemCapability.Multimedia.Image.ImageSource
5438
5439**Parameters**
5440
5441| Name  | Type                                 | Mandatory| Description                      |
5442| -------- | ------------------------------------- | ---- | -------------------------- |
5443| options  | [DecodingOptions](#decodingoptions7)  | No  | Decoding options.                |
5444
5445**Return value**
5446
5447| Type                            | Description                 |
5448| -------------------------------- | --------------------- |
5449| Promise<Array<[PixelMap](#pixelmap7)>> | Promise used to return an array of PixelMap objects.|
5450
5451**Error codes**
5452
5453For details about the error codes, see [Image Error Codes](errorcode-image.md).
5454
5455| ID| Error Message|
5456| ------- | --------------------------------------------|
5457| 62980096| Operation failed.Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.              |
5458| 62980099 | The shared memory data is abnormal. |
5459| 62980101 | The image data is abnormal. |
5460| 62980103| The image data is not supported.             |
5461| 62980106 | The image data is too large. This status code is thrown when an error occurs during the process of checking size. |
5462| 62980109 | Failed to crop the image. |
5463| 62980110| The image source data is incorrect.             |
5464| 62980111| The image source data is incomplete.           |
5465| 62980112 | The image format does not match. |
5466| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted.            |
5467| 62980115 | Invalid image parameter. |
5468| 62980116 | Failed to decode the image. |
5469| 62980118| Failed to create the image plugin.             |
5470| 62980122 | Failed to decode the image header. |
5471| 62980137 | Invalid media operation. |
5472| 62980173 | The DMA memory does not exist. |
5473| 62980174 | The DMA memory data is abnormal. |
5474
5475**Example**
5476
5477```ts
5478import { BusinessError } from '@kit.BasicServicesKit';
5479
5480let decodeOpts: image.DecodingOptions = {
5481  sampleSize: 1,
5482  editable: true,
5483  desiredSize: { width: 198, height: 202 },
5484  rotate: 0,
5485  desiredPixelFormat: image.PixelMapFormat.RGBA_8888,
5486  index: 0,
5487};
5488imageSourceApi.createPixelMapList(decodeOpts).then((pixelMapList: Array<image.PixelMap>) => {
5489  console.info('Succeeded in creating pixelMapList object.');
5490}).catch((err: BusinessError) => {
5491  console.error(`Failed to create pixelMapList object, error code is ${err}`);
5492})
5493```
5494
5495### createPixelMapList<sup>10+</sup>
5496
5497createPixelMapList(callback: AsyncCallback<Array\<PixelMap>>): void
5498
5499Creates an array of PixelMap objects based on the default parameters. This API uses an asynchronous callback to return the result. For dynamic images such as GIF and WebP images, this API returns the data of each frame of the image. For static images, this API returns the data of the unique frame of the image.
5500
5501> **NOTE**
5502>
5503> This function decodes all frames at once. If the number of frames is high or the size of individual frames is large, it can lead to significant memory usage. In these cases, you are advised to use the **Image** component for displaying animations. The **Image** component decodes frames one by one, which uses less memory than this function.
5504
5505**System capability**: SystemCapability.Multimedia.Image.ImageSource
5506
5507**Parameters**
5508
5509| Name    | Type                                 | Mandatory| Description                      |
5510| -------- | ------------------------------------- | ---- | -------------------------- |
5511| callback | AsyncCallback<Array<[PixelMap](#pixelmap7)>> | Yes  | Callback used to return the result. If the operation is successful, **err** is undefined and **data** is the array of PixelMap objects obtained; otherwise, **err** is an error object. |
5512
5513**Error codes**
5514
5515For details about the error codes, see [Image Error Codes](errorcode-image.md).
5516
5517| ID| Error Message|
5518| ------- | --------------------------------------------|
5519| 62980096 | Operation failed.Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.             |
5520| 62980099 | The shared memory data is abnormal.  |
5521| 62980101 | The image data is abnormal.          |
5522| 62980103 | The image data is not supported.         |
5523| 62980106 | The image data is too large. This status code is thrown when an error occurs during the process of checking size. |
5524| 62980109 | Failed to crop the image.            |
5525| 62980110 | The image source data is incorrect.      |
5526| 62980111 | The image source data is incomplete. |
5527| 62980112 | The image format does not match.       |
5528| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted.            |
5529| 62980115 | Invalid image parameter.      |
5530| 62980116 | Failed to decode the image.         |
5531| 62980118 | Failed to create the image plugin.   |
5532| 62980122 | Failed to decode the image header.   |
5533| 62980137 | Invalid media operation.     |
5534| 62980173 | The DMA memory does not exist.        |
5535| 62980174 | The DMA memory data is abnormal.    |
5536
5537**Example**
5538
5539```ts
5540import { BusinessError } from '@kit.BasicServicesKit';
5541
5542imageSourceApi.createPixelMapList((err: BusinessError, pixelMapList: Array<image.PixelMap>) => {
5543  if (err) {
5544    console.error(`Failed to create pixelMapList object, error code is ${err}`);
5545  } else {
5546    console.info('Succeeded in creating pixelMapList object.');
5547  }
5548})
5549```
5550
5551### createPixelMapList<sup>10+</sup>
5552
5553createPixelMapList(options: DecodingOptions, callback: AsyncCallback<Array\<PixelMap>>): void
5554
5555Creates an array of PixelMap objects based on decoding options. This API uses an asynchronous callback to return the result. For dynamic images such as GIF and WebP images, this API returns the data of each frame of the image. For static images, this API returns the data of the unique frame of the image.
5556
5557> **NOTE**
5558>
5559> This function decodes all frames at once. If the number of frames is high or the size of individual frames is large, it can lead to significant memory usage. In these cases, you are advised to use the **Image** component for displaying animations. The **Image** component decodes frames one by one, which uses less memory than this function.
5560
5561**System capability**: SystemCapability.Multimedia.Image.ImageSource
5562
5563**Parameters**
5564
5565| Name  | Type                | Mandatory| Description                              |
5566| -------- | -------------------- | ---- | ---------------------------------- |
5567| options | [DecodingOptions](#decodingoptions7) | Yes| Decoding options.|
5568| callback | AsyncCallback<Array<[PixelMap](#pixelmap7)>> | Yes  | Callback used to return the result. If the operation is successful, **err** is undefined and **data** is the array of PixelMap objects obtained; otherwise, **err** is an error object. |
5569
5570**Error codes**
5571
5572For details about the error codes, see [Image Error Codes](errorcode-image.md).
5573
5574| ID| Error Message|
5575| ------- | --------------------------------------------|
5576| 62980096 | Operation failed.Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.            |
5577| 62980099 | The shared memory data is abnormal.  |
5578| 62980101 | The image data is abnormal.         |
5579| 62980103 | The image data is not supported.        |
5580| 62980106 | The image data is too large. This status code is thrown when an error occurs during the process of checking size. |
5581| 62980109 | Failed to crop the image.           |
5582| 62980110 | The image source data is incorrect.      |
5583| 62980111 | The image source data is incomplete. |
5584| 62980112 | The image format does not match.        |
5585| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted.            |
5586| 62980115 | Invalid image parameter.      |
5587| 62980116 | Failed to decode the image.         |
5588| 62980118 | Failed to create the image plugin.  |
5589| 62980122 | Failed to decode the image header.   |
5590| 62980137 | Invalid media operation.      |
5591| 62980173 | The DMA memory does not exist.         |
5592| 62980174 | The DMA memory data is abnormal.     |
5593
5594**Example**
5595
5596```ts
5597import { BusinessError } from '@kit.BasicServicesKit';
5598
5599let decodeOpts: image.DecodingOptions = {
5600  sampleSize: 1,
5601  editable: true,
5602  desiredSize: { width: 198, height: 202 },
5603  rotate: 0,
5604  desiredPixelFormat: image.PixelMapFormat.RGBA_8888,
5605  index: 0,
5606};
5607imageSourceApi.createPixelMapList(decodeOpts, (err: BusinessError, pixelMapList: Array<image.PixelMap>) => {
5608  if (err) {
5609    console.error(`Failed to create pixelMapList object, error code is ${err}`);
5610  } else {
5611    console.info('Succeeded in creating pixelMapList object.');
5612  }
5613})
5614```
5615
5616### createPixelMapUsingAllocator<sup>15+</sup>
5617
5618createPixelMapUsingAllocator(options?: DecodingOptions, allocatorType?: AllocatorType): Promise\<PixelMap>
5619
5620Creates a PixelMap object based on decoding options and memory type. This API uses a promise to return the result. For details about how to use the API, see [Allocating Memory for Image Decoding (ArkTS)](../../media/image/image-allocator-type.md).
5621
5622**System capability**: SystemCapability.Multimedia.Image.ImageSource
5623
5624**Parameters**
5625
5626| Name       | Type                                | Mandatory| Description                    |
5627| ------------- | ------------------------------------ | ---- | ------------------------ |
5628| options        | [DecodingOptions](#decodingoptions7) | No  | Decoding options.              |
5629| allocatorType | [AllocatorType](#allocatortype15)   | No  | Type of the memory. The default value is **AllocatorType.AUTO**.|
5630
5631**Return value**
5632
5633| Type                            | Description                       |
5634| -------------------------------- | --------------------------- |
5635| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the PixelMap object.|
5636
5637**Error codes**
5638
5639For details about the error codes, see [Image Error Codes](errorcode-image.md).
5640
5641| ID| Error Message                                                    |
5642| -------- | ------------------------------------------------------------ |
5643| 401      | Parameter error.Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types;3.Parameter verification failed. |
5644| 7700101  | Bad source. e.g.,1. Image has invalid width or height. 2. Image source incomplete. 3. Read image data failed. 4. Codec create failed. |
5645| 7700102  | Unsupported mimetype.                                        |
5646| 7700103  | Image too large.  This status code is thrown when an error occurs during the process of checking size. |
5647| 7700201  | Unsupported allocator type, e.g., use share memory to decode a HDR image as only DMA supported hdr metadata. |
5648| 7700203  | Unsupported options, e.g., cannot convert image into desired pixel format. |
5649| 7700301  | Failed to decode image.                                      |
5650| 7700302  | Failed to allocate memory.                                   |
5651
5652**Example**
5653
5654<!--code_no_check-->
5655```ts
5656import { common } from '@kit.AbilityKit';
5657import image from '@ohos.multimedia.image';
5658
5659// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
5660let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
5661// 'test.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
5662let filePath: string = context.filesDir + "/test.jpg";
5663let imageSource = image.createImageSource(filePath);
5664let decodingOptions: image.DecodingOptions = {
5665  editable: true,
5666  desiredSize: { width: 3072, height: 4096 },
5667  rotate: 10,
5668  desiredPixelFormat: image.PixelMapFormat.RGBA_8888,
5669  desiredRegion: { size: { width: 3072, height: 4096 }, x: 0, y: 0 },
5670  cropAndScaleStrategy: image.CropAndScaleStrategy.CROP_FIRST,
5671  index: 0
5672};
5673let pixelmap = imageSource.createPixelMapUsingAllocator(decodingOptions, image.AllocatorType.AUTO);
5674if (pixelmap != undefined) {
5675  console.info('Succeeded in creating pixelMap object.');
5676} else {
5677  console.error('Failed to create pixelMap.');
5678}
5679```
5680
5681### createPixelMapUsingAllocatorSync<sup>15+</sup>
5682
5683createPixelMapUsingAllocatorSync(options?: DecodingOptions, allocatorType?: AllocatorType): PixelMap
5684
5685Creates a PixelMap object based on decoding options and memory type. This API returns the result synchronously. For details about how to use the API, see [Allocating Memory for Image Decoding (ArkTS)](../../media/image/image-allocator-type.md).
5686
5687**System capability**: SystemCapability.Multimedia.Image.ImageSource
5688
5689**Parameters**
5690
5691| Name       | Type                                | Mandatory| Description                    |
5692| ------------- | ------------------------------------ | ---- | ------------------------ |
5693| options        | [DecodingOptions](#decodingoptions7) | No  | Decoding options.              |
5694| allocatorType | [AllocatorType](#allocatortype15)   | No  | Type of the memory. The default value is **AllocatorType.AUTO**.|
5695
5696**Return value**
5697
5698| Type                  | Description                  |
5699| ---------------------- | ---------------------- |
5700| [PixelMap](#pixelmap7) | PixelMap object.|
5701
5702**Error codes**
5703
5704For details about the error codes, see [Image Error Codes](errorcode-image.md).
5705
5706| ID| Error Message                                                    |
5707| -------- | ------------------------------------------------------------ |
5708| 401      | Parameter error.Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types;3.Parameter verification failed. |
5709| 7700101  | Bad source. e.g.,1. Image has invalid width or height. 2. Image source incomplete. 3. Read image data failed. 4. Codec create failed. |
5710| 7700102  | Unsupported mimetype.                                        |
5711| 7700103  | Image too large.  This status code is thrown when an error occurs during the process of checking size. |
5712| 7700201  | Unsupported allocator type, e.g., use share memory to decode a HDR image as only DMA supported hdr metadata. |
5713| 7700203  | Unsupported options, e.g., cannot convert image into desired pixel format. |
5714| 7700301  | Failed to decode image.                                      |
5715| 7700302  | Failed to allocate memory.                                   |
5716
5717**Example**
5718
5719<!--code_no_check-->
5720```ts
5721import { common } from '@kit.AbilityKit';
5722import image from '@ohos.multimedia.image';
5723
5724// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
5725let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
5726// 'test.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
5727let filePath: string = context.filesDir + "/test.jpg";
5728let imageSource = image.createImageSource(filePath);
5729let decodingOptions: image.DecodingOptions = {
5730  editable: true,
5731  desiredSize: { width: 3072, height: 4096 },
5732  rotate: 10,
5733  desiredPixelFormat: image.PixelMapFormat.RGBA_8888,
5734  desiredRegion: { size: { width: 3072, height: 4096 }, x: 0, y: 0 },
5735  cropAndScaleStrategy: image.CropAndScaleStrategy.CROP_FIRST,
5736  index: 0
5737};
5738let pixelmap = imageSource.createPixelMapUsingAllocatorSync(decodingOptions, image.AllocatorType.AUTO);
5739if (pixelmap != undefined) {
5740  console.info('Succeeded in creating pixelMap object.');
5741} else {
5742  console.error('Failed to create pixelMap.');
5743}
5744```
5745
5746### getDelayTimeList<sup>10+</sup>
5747
5748getDelayTimeList(callback: AsyncCallback<Array\<number>>): void
5749
5750Obtains an array of delay times. This API uses an asynchronous callback to return the result. This API applies only to images in GIF or WebP format.
5751
5752**System capability**: SystemCapability.Multimedia.Image.ImageSource
5753
5754**Parameters**
5755
5756| Name  | Type                | Mandatory| Description                              |
5757| -------- | -------------------- | ---- | ---------------------------------- |
5758| callback | AsyncCallback<Array\<number>> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the array of delay times obtained; otherwise, **err** is an error object.|
5759
5760**Error codes**
5761
5762For details about the error codes, see [Image Error Codes](errorcode-image.md).
5763
5764| ID| Error Message|
5765| ------- | --------------------------------------------|
5766| 62980096| Operation failed.Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.              |
5767| 62980110| The image source data is incorrect.             |
5768| 62980111| The image source data is incomplete.            |
5769| 62980112 | The image format does not match. |
5770| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted.            |
5771| 62980115 | Invalid image parameter. |
5772| 62980116| Failed to decode the image. |
5773| 62980118| Failed to create the image plugin. |
5774| 62980122| Failed to decode the image header. |
5775| 62980137 | Invalid media operation. |
5776| 62980149 | Invalid MIME type for the image source. |
5777
5778**Example**
5779
5780```ts
5781import { BusinessError } from '@kit.BasicServicesKit';
5782
5783imageSourceApi.getDelayTimeList((err: BusinessError, delayTimes: Array<number>) => {
5784  if (err) {
5785    console.error(`Failed to get delayTimes object.code is ${err.code},message is ${err.message}`);
5786  } else {
5787    console.info('Succeeded in getting delayTimes object.');
5788  }
5789})
5790```
5791
5792### getDelayTimeList<sup>10+</sup>
5793
5794getDelayTimeList(): Promise<Array\<number>>
5795
5796Obtains an array of delay times. This API uses a promise to return the result. This API applies only to images in GIF or WebP format.
5797
5798**System capability**: SystemCapability.Multimedia.Image.ImageSource
5799
5800**Return value**
5801
5802| Type          | Description                       |
5803| -------------- | --------------------------- |
5804| Promise<Array\<number>> | Promise used to return an array of delay times.|
5805
5806**Error codes**
5807
5808For details about the error codes, see [Image Error Codes](errorcode-image.md).
5809
5810| ID| Error Message|
5811| ------- | --------------------------------------------|
5812| 62980096 | Operation failed.Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.             |
5813| 62980110 | The image source data is incorrect.      |
5814| 62980111 | The image source data is incomplete. |
5815| 62980112 | The image format does not match.        |
5816| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted.            |
5817| 62980115 | Invalid image parameter.      |
5818| 62980116 | Failed to decode the image.          |
5819| 62980118 | Failed to create the image plugin.  |
5820| 62980122 | Failed to decode the image header.   |
5821| 62980137 | Invalid media operation.      |
5822| 62980149 | Invalid MIME type for the image source.      |
5823
5824**Example**
5825
5826```ts
5827import { BusinessError } from '@kit.BasicServicesKit';
5828
5829imageSourceApi.getDelayTimeList().then((delayTimes: Array<number>) => {
5830  console.info('Succeeded in getting delayTimes object.');
5831}).catch((err: BusinessError) => {
5832  console.error(`Failed to get delayTimes object.code is ${err.code},message is ${err.message}`);
5833})
5834```
5835
5836### getFrameCount<sup>10+</sup>
5837
5838getFrameCount(callback: AsyncCallback\<number>): void
5839
5840Obtains the number of frames. This API uses an asynchronous callback to return the result.
5841
5842**System capability**: SystemCapability.Multimedia.Image.ImageSource
5843
5844**Parameters**
5845
5846| Name  | Type                | Mandatory| Description                              |
5847| -------- | -------------------- | ---- | ---------------------------------- |
5848| callback | AsyncCallback\<number> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of frames obtained; otherwise, **err** is an error object.|
5849
5850**Error codes**
5851
5852For details about the error codes, see [Image Error Codes](errorcode-image.md).
5853
5854| ID| Error Message|
5855| ------- | --------------------------------------------|
5856| 62980096| Operation failed.Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.             |
5857| 62980110| The image source data is incorrect. |
5858| 62980111| The image source data is incomplete. |
5859| 62980112| The image format does not match. |
5860| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted.            |
5861| 62980115| Invalid image parameter. |
5862| 62980116| Failed to decode the image. |
5863| 62980118| Failed to create the image plugin. |
5864| 62980122| Failed to decode the image header. |
5865| 62980137| Invalid media operation. |
5866
5867**Example**
5868
5869```ts
5870import { BusinessError } from '@kit.BasicServicesKit';
5871
5872imageSourceApi.getFrameCount((err: BusinessError, frameCount: number) => {
5873  if (err) {
5874    console.error(`Failed to get frame count.code is ${err.code},message is ${err.message}`);
5875  } else {
5876    console.info('Succeeded in getting frame count.');
5877  }
5878})
5879```
5880
5881### getFrameCount<sup>10+</sup>
5882
5883getFrameCount(): Promise\<number>
5884
5885Obtains the number of frames. This API uses a promise to return the result.
5886
5887**System capability**: SystemCapability.Multimedia.Image.ImageSource
5888
5889**Return value**
5890
5891| Type          | Description                       |
5892| -------------- | --------------------------- |
5893| Promise\<number> | Promise used to return the number of frames.|
5894
5895**Error codes**
5896
5897For details about the error codes, see [Image Error Codes](errorcode-image.md).
5898
5899| ID| Error Message|
5900| ------- | --------------------------------------------|
5901| 62980096 | Operation failed.Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.             |
5902| 62980110 | The image source data is incorrect.      |
5903| 62980111 | The image source data is incomplete. |
5904| 62980112 | The image format does not match.        |
5905| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted.            |
5906| 62980115 | Invalid image parameter.      |
5907| 62980116 | Failed to decode the image.          |
5908| 62980118 | Failed to create the image plugin.   |
5909| 62980122 | Failed to decode the image header.  |
5910| 62980137 | Invalid media operation.      |
5911
5912**Example**
5913
5914```ts
5915import { BusinessError } from '@kit.BasicServicesKit';
5916
5917imageSourceApi.getFrameCount().then((frameCount: number) => {
5918  console.info('Succeeded in getting frame count.');
5919}).catch((err: BusinessError) => {
5920  console.error(`Failed to get frame count.code is ${err.code},message is ${err.message}`);
5921})
5922```
5923
5924### getDisposalTypeList<sup>12+</sup>
5925
5926getDisposalTypeList(): Promise\<Array\<number>>
5927
5928Obtains the list of disposal types. This API uses a promise to return the result. It is used only for GIF images.
5929
5930**System capability**: SystemCapability.Multimedia.Image.ImageSource
5931
5932**Return value**
5933
5934| Type          | Description                       |
5935| -------------- | --------------------------- |
5936| Promise\<Array\<number>> | Promise used to return an array of disposal types.|
5937
5938**Error codes**
5939
5940For details about the error codes, see [Image Error Codes](errorcode-image.md).
5941
5942| ID| Error Message|
5943| ------- | --------------------------------------------|
5944| 62980096 | Operation failed.Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.      |
5945| 62980101 | The image data is abnormal. |
5946| 62980137 | Invalid media operation.        |
5947| 62980149 | Invalid MIME type for the image source.      |
5948
5949**Example**
5950
5951```ts
5952import { BusinessError } from '@kit.BasicServicesKit';
5953imageSourceApi.getDisposalTypeList().then((disposalTypes: Array<number>) => {
5954  console.info('Succeeded in getting disposalTypes object.');
5955}).catch((err: BusinessError) => {
5956  console.error(`Failed to get disposalTypes object.code ${err.code},message is ${err.message}`);
5957})
5958```
5959
5960### release
5961
5962release(callback: AsyncCallback\<void>): void
5963
5964Releases this ImageSource instance. This API uses an asynchronous callback to return the result.
5965
5966ArkTS supports memory reclamation. Even if the application does not call **release()**, the memory of the ImageSource object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
5967
5968**System capability**: SystemCapability.Multimedia.Image.ImageSource
5969
5970**Parameters**
5971
5972| Name  | Type                | Mandatory| Description                              |
5973| -------- | -------------------- | ---- | ---------------------------------- |
5974| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. |
5975
5976**Example**
5977
5978```ts
5979import { BusinessError } from '@kit.BasicServicesKit';
5980
5981imageSourceApi.release((err: BusinessError) => {
5982  if (err) {
5983    console.error(`Failed to release the image source instance.code ${err.code},message is ${err.message}`);
5984  } else {
5985    console.info('Succeeded in releasing the image source instance.');
5986  }
5987})
5988```
5989
5990### release
5991
5992release(): Promise\<void>
5993
5994Releases this ImageSource instance. This API uses a promise to return the result.
5995
5996ArkTS supports memory reclamation. Even if the application does not call **release()**, the memory of the ImageSource object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
5997
5998**System capability**: SystemCapability.Multimedia.Image.ImageSource
5999
6000**Return value**
6001
6002| Type          | Description                       |
6003| -------------- | --------------------------- |
6004| Promise\<void> |  Promise that returns no value.|
6005
6006**Example**
6007
6008```ts
6009import { BusinessError } from '@kit.BasicServicesKit';
6010
6011imageSourceApi.release().then(() => {
6012  console.info('Succeeded in releasing the image source instance.');
6013}).catch((error: BusinessError) => {
6014  console.error(`Failed to release the image source instance.code ${error.code},message is ${error.message}`);
6015})
6016```
6017
6018## image.getImageSourceSupportedFormats<sup>20+</sup>
6019
6020getImageSourceSupportedFormats(): string[]
6021
6022Obtains the supported decoding formats, represented by MIME types.
6023
6024**System capability**: SystemCapability.Multimedia.Image.Core
6025
6026**Return value**
6027
6028| Type    | Description                                      |
6029| -------- | ------------------------------------------ |
6030| string[] | List of supported encoding formats (MIME types).|
6031
6032**Example**
6033
6034```ts
6035import { image } from '@kit.ImageKit';
6036function GetImageSourceSupportedFormats() {
6037    let formats = image.getImageSourceSupportedFormats();
6038    console.info('formats:', formats);
6039}
6040```
6041
6042## image.createImagePacker
6043
6044createImagePacker(): ImagePacker
6045
6046Creates an ImagePacker instance.
6047
6048**Atomic service API**: This API can be used in atomic services since API version 11.
6049
6050**System capability**: SystemCapability.Multimedia.Image.ImagePacker
6051
6052**Return value**
6053
6054| Type                       | Description                 |
6055| --------------------------- | --------------------- |
6056| [ImagePacker](#imagepacker) | ImagePacker instance created.|
6057
6058**Example**
6059
6060```ts
6061const imagePackerApi: image.ImagePacker = image.createImagePacker();
6062```
6063
6064## ImagePacker
6065
6066Provides APIs to compress and encode images. Before calling any API in ImagePacker, you must use [createImagePacker](#imagecreateimagepacker) to create an ImagePacker object. Currently, this class applies only to images in .jpeg, .webp, .png, or heif<sup>12+</sup> (depending on the hardware).
6067
6068### Properties
6069
6070**System capability**: SystemCapability.Multimedia.Image.ImagePacker
6071
6072| Name            | Type          | Read Only| Optional| Description                      |
6073| ---------------- | -------------- | ---- | ---- | -------------------------- |
6074| supportedFormats | Array\<string> | Yes  | No  | Supported formats, including .jpeg, .webp, .png, and heic<sup>12+</sup> (depending on the hardware).|
6075
6076### packToData<sup>13+</sup>
6077
6078packToData(source: ImageSource, options: PackingOption): Promise\<ArrayBuffer>
6079
6080Compresses or re-encodes an image. This API uses a promise to return the result.
6081
6082**Atomic service API**: This API can be used in atomic services since API version 13.
6083
6084**System capability**: SystemCapability.Multimedia.Image.ImagePacker
6085
6086**Parameters**
6087
6088| Name| Type                           | Mandatory| Description          |
6089| ------ | ------------------------------- | ---- | -------------- |
6090| source | [ImageSource](#imagesource)     | Yes  | Image source to compress or re-encode.|
6091| options | [PackingOption](#packingoption) | Yes  | Encoding parameters.|
6092
6093**Error codes**
6094
6095For details about the error codes, see [Image Error Codes](errorcode-image.md).
6096
6097| ID| Error Message|
6098| ------- | --------------------------------------------|
6099| 401 | If the parameter is invalid. |
6100| 62980096| Operation failed.Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.              |
6101| 62980101 | The image data is abnormal. |
6102| 62980106 | The image data is too large. This status code is thrown when an error occurs during the process of checking size. |
6103| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted.            |
6104| 62980119 | Failed to encode the image. |
6105| 62980120 | Add pixelmap out of range. |
6106| 62980172 | Failed to encode icc. |
6107| 62980252 | Failed to create surface. |
6108
6109**Return value**
6110
6111| Type                        | Description                                         |
6112| ---------------------------- | --------------------------------------------- |
6113| Promise\<ArrayBuffer>        | Promise used to return the compressed or encoded image data.|
6114
6115**Example**
6116
6117<!--code_no_check-->
6118```ts
6119import { common } from '@kit.AbilityKit';
6120import { BusinessError } from '@kit.BasicServicesKit';
6121
6122// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
6123let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
6124// 'test.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
6125let filePath: string = context.filesDir + "/test.jpg";
6126const imageSourceApi: image.ImageSource = image.createImageSource(filePath);
6127let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }
6128const imagePackerApi: image.ImagePacker = image.createImagePacker();
6129imagePackerApi.packToData(imageSourceApi, packOpts)
6130  .then((data: ArrayBuffer) => {
6131    console.info('Succeeded in packing the image.');
6132  }).catch((error: BusinessError) => {
6133    console.error(`Failed to pack the image.code ${error.code},message is ${error.message}`);
6134  })
6135```
6136
6137### packToData<sup>13+</sup>
6138
6139packToData(source: PixelMap, options: PackingOption): Promise\<ArrayBuffer>
6140
6141Compresses or re-encodes an image. This API uses a promise to return the result.
6142
6143> **NOTE**
6144>
6145> If error code 401 is returned, the parameters are abnormal. The possible cause is that the PixelMap object is released in advance. You need to check the code and ensure that the PixelMap object is released after this API is called.
6146
6147**Atomic service API**: This API can be used in atomic services since API version 13.
6148
6149**System capability**: SystemCapability.Multimedia.Image.ImagePacker
6150
6151**Parameters**
6152
6153| Name| Type                           | Mandatory| Description              |
6154| ------ | ------------------------------- | ---- | ------------------ |
6155| source | [PixelMap](#pixelmap7)           | Yes  | PixelMap to compress or re-encode.|
6156| options | [PackingOption](#packingoption) | Yes  | Encoding parameters.    |
6157
6158**Return value**
6159
6160| Type                 | Description                                        |
6161| --------------------- | -------------------------------------------- |
6162| Promise\<ArrayBuffer> | Promise used to return the compressed or encoded image data.|
6163
6164**Error codes**
6165
6166For details about the error codes, see [Image Error Codes](errorcode-image.md).
6167
6168| ID| Error Message|
6169| ------- | --------------------------------------------|
6170| 401 | If the parameter is invalid. |
6171| 62980096| Operation failed.Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.              |
6172| 62980101 | The image data is abnormal. |
6173| 62980106 | The image data is too large. This status code is thrown when an error occurs during the process of checking size. |
6174| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted.            |
6175| 62980119 | Failed to encode the image. |
6176| 62980120 | Add pixelmap out of range. |
6177| 62980172 | Failed to encode icc. |
6178| 62980252 | Failed to create surface. |
6179
6180**Example**
6181
6182```ts
6183import { BusinessError } from '@kit.BasicServicesKit';
6184
6185const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4.
6186let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
6187image.createPixelMap(color, opts).then((pixelMap: image.PixelMap) => {
6188  let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }
6189  const imagePackerApi: image.ImagePacker = image.createImagePacker();
6190  imagePackerApi.packToData(pixelMap, packOpts)
6191    .then((data: ArrayBuffer) => {
6192      console.info('Succeeded in packing the image.');
6193    }).catch((error: BusinessError) => {
6194    console.error(`Failed to pack the image.code ${error.code},message is ${error.message}`);
6195  })
6196}).catch((error: BusinessError) => {
6197  console.error(`Failed to create PixelMap.code ${error.code},message is ${error.message}`);
6198})
6199```
6200
6201### packing<sup>13+</sup>
6202
6203packing(picture: Picture, options: PackingOption): Promise\<ArrayBuffer>
6204
6205Compresses or re-encodes an image. This API uses a promise to return the result.
6206
6207**System capability**: SystemCapability.Multimedia.Image.ImagePacker
6208
6209**Parameters**
6210
6211| Name          | Type                                                | Mandatory| Description                |
6212| ---------------- | ---------------------------------------------------- | ---- | -------------------- |
6213| picture | [Picture](#picture13)                           | Yes  | Picture to compress or re-encode.|
6214| options          | [PackingOption](#packingoption) | Yes  | Encoding parameters.      |
6215
6216**Return value**
6217
6218| Type                 | Description                                 |
6219| --------------------- | ------------------------------------- |
6220| Promise\<ArrayBuffer> | Promise used to return the compressed or encoded image data.|
6221
6222**Error codes**
6223
6224For details about the error codes, see [Image Error Codes](errorcode-image.md).
6225
6226| ID| Error Message                                                    |
6227| -------- | ------------------------------------------------------------ |
6228| 401      | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
6229| 7800301  | Encode failed.                                         |
6230
6231**Example**
6232
6233```ts
6234import { BusinessError } from '@kit.BasicServicesKit';
6235import { image } from '@kit.ImageKit';
6236
6237async function Packing(context: Context) {
6238  const resourceMgr = context.resourceManager;
6239  const rawFile = await resourceMgr.getRawFileContent("test.jpg");
6240  let ops: image.SourceOptions = {
6241    sourceDensity: 98,
6242  }
6243  let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
6244  let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap();
6245  let pictureObj: image.Picture = image.createPicture(commodityPixelMap);
6246  const imagePackerApi: image.ImagePacker = image.createImagePacker();
6247  let funcName = "Packing";
6248  if (imagePackerApi != null) {
6249    let opts: image.PackingOption = {
6250      format: "image/jpeg",
6251      quality: 98,
6252      bufferSize: 10,
6253      desiredDynamicRange: image.PackingDynamicRange.AUTO,
6254      needsPackProperties: true};
6255    await imagePackerApi.packing(pictureObj, opts).then((data: ArrayBuffer) => {
6256        console.info(funcName, 'Succeeded in packing the image.'+ data);
6257      }).catch((error: BusinessError) => {
6258        console.error(funcName, 'Failed to pack the image.code ${error.code},message is ${error.message}');
6259      });
6260  }
6261}
6262```
6263
6264### packToDataFromPixelmapSequence<sup>18+</sup>
6265
6266packToDataFromPixelmapSequence(pixelmapSequence: Array\<PixelMap>, options: PackingOptionsForSequence): Promise\<ArrayBuffer>
6267
6268Encodes multiple PixelMap objects into GIF data. This API uses a promise to return the result.
6269
6270**System capability**: SystemCapability.Multimedia.Image.ImagePacker
6271
6272**Parameters**
6273
6274| Name          | Type                                                     | Mandatory| Description                  |
6275| ---------------- | --------------------------------------------------------- | ---- | ---------------------- |
6276| pixelmapSequence | Array\<[PixelMap](#pixelmap7)>                            | Yes  | PixelMaps to encode.|
6277| options          | [PackingOptionsForSequence](#packingoptionsforsequence18) | Yes  | Options for encoding animated images.        |
6278
6279**Return value**
6280
6281| Type                 | Description                           |
6282| --------------------- | ------------------------------- |
6283| Promise\<ArrayBuffer> | Promise used to return the encoded data.|
6284
6285**Error codes**
6286
6287For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Image Error Codes](errorcode-image.md).
6288
6289| ID| Error Message                                                    |
6290| -------- | ------------------------------------------------------------ |
6291| 401      | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
6292| 7800201  | Unsupported packing options.                                 |
6293| 7800301  | Failed to encode image.                                      |
6294
6295**Example**
6296
6297<!--code_no_check-->
6298```ts
6299import { common } from '@kit.AbilityKit';
6300import { BusinessError } from '@ohos.base';
6301import image from "@ohos.multimedia.image";
6302
6303// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
6304let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
6305const resourceMgr = context.resourceManager;
6306// 'moving_test.gif' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
6307const fileData = resourceMgr.getRawFileContent('moving_test.gif');
6308const color = fileData.buffer;
6309let imageSource = image.createImageSource(color);
6310let pixelMapList = imageSource.createPixelMapList();
6311let ops: image.PackingOptionsForSequence = {
6312  frameCount: 3, // Set the number of frames in GIF encoding to 3.
6313  delayTimeList: [10, 10, 10], // Set the delay time of three frames in GIF encoding to 100 ms, 100 ms, and 100 ms, respectively.
6314  disposalTypes: [3, 2, 3], // Specify the frame transition modes of the three frames in GIF encoding as 3 (restore to the previous state), 2 (restore to the background color), and 3 (restore to the previous state).
6315  loopCount: 0 // Set the number of loops in GIF encoding to infinite.
6316};
6317let Packer = image.createImagePacker();
6318Packer.packToDataFromPixelmapSequence(pixelMapList, ops)
6319  .then((data: ArrayBuffer) => {
6320    console.info('Succeeded in packing.');
6321  }).catch((error: BusinessError) => {
6322  console.error('Failed to packing.');
6323  })
6324```
6325
6326### packing<sup>(deprecated)</sup>
6327
6328packing(source: ImageSource, option: PackingOption, callback: AsyncCallback\<ArrayBuffer>): void
6329
6330Compresses or re-encodes an image. This API uses an asynchronous callback to return the result.
6331
6332> **NOTE**
6333>
6334> This API is supported since API version 6 and deprecated since API version 13. Use [packToData](#packtodata13) instead.
6335
6336**Atomic service API**: This API can be used in atomic services since API version 11.
6337
6338**System capability**: SystemCapability.Multimedia.Image.ImagePacker
6339
6340**Parameters**
6341
6342| Name  | Type                              | Mandatory| Description                              |
6343| -------- | ---------------------------------- | ---- | ---------------------------------- |
6344| source   | [ImageSource](#imagesource)        | Yes  | Image source to compress or re-encode.                    |
6345| option   | [PackingOption](#packingoption)    | Yes  | Encoding parameters.                     |
6346| callback | AsyncCallback\<ArrayBuffer>        | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the compressed or encoded image data; otherwise, **err** is an error object. |
6347
6348**Example**
6349
6350<!--code_no_check-->
6351```ts
6352import { common } from '@kit.AbilityKit';
6353import { BusinessError } from '@kit.BasicServicesKit';
6354
6355// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
6356let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
6357// 'test.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
6358let filePath: string = context.filesDir + "/test.jpg";
6359const imageSourceApi: image.ImageSource = image.createImageSource(filePath);
6360let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 };
6361const imagePackerApi: image.ImagePacker = image.createImagePacker();
6362imagePackerApi.packing(imageSourceApi, packOpts, (err: BusinessError, data: ArrayBuffer) => {
6363  if (err) {
6364    console.error(`Failed to pack the image.code ${err.code},message is ${err.message}`);
6365  } else {
6366    console.info('Succeeded in packing the image.');
6367  }
6368})
6369```
6370
6371### packing<sup>(deprecated)</sup>
6372
6373packing(source: ImageSource, option: PackingOption): Promise\<ArrayBuffer>
6374
6375Compresses or re-encodes an image. This API uses a promise to return the result.
6376
6377> **NOTE**
6378>
6379> This API is supported since API version 6 and deprecated since API version 13. Use [packToData](#packtodata13) instead.
6380
6381**Atomic service API**: This API can be used in atomic services since API version 11.
6382
6383**System capability**: SystemCapability.Multimedia.Image.ImagePacker
6384
6385**Parameters**
6386
6387| Name| Type                           | Mandatory| Description          |
6388| ------ | ------------------------------- | ---- | -------------- |
6389| source | [ImageSource](#imagesource)     | Yes  | Image source to compress or re-encode.|
6390| option | [PackingOption](#packingoption) | Yes  | Encoding parameters.|
6391
6392**Return value**
6393
6394| Type                        | Description                                         |
6395| ---------------------------- | --------------------------------------------- |
6396| Promise\<ArrayBuffer>        | Promise used to return the compressed or encoded image data.|
6397
6398**Example**
6399
6400<!--code_no_check-->
6401```ts
6402import { common } from '@kit.AbilityKit';
6403import { BusinessError } from '@kit.BasicServicesKit';
6404
6405// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
6406let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
6407// 'test.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
6408let filePath: string = context.filesDir + "/test.jpg";
6409const imageSourceApi: image.ImageSource = image.createImageSource(filePath);
6410let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }
6411const imagePackerApi: image.ImagePacker = image.createImagePacker();
6412imagePackerApi.packing(imageSourceApi, packOpts)
6413  .then((data: ArrayBuffer) => {
6414    console.info('Succeeded in packing the image.');
6415  }).catch((error: BusinessError) => {
6416    console.error(`Failed to pack the image.code ${error.code},message is ${error.message}`);
6417  })
6418```
6419
6420### packing<sup>(deprecated)</sup>
6421
6422packing(source: PixelMap, option: PackingOption, callback: AsyncCallback\<ArrayBuffer>): void
6423
6424Compresses or re-encodes an image. This API uses an asynchronous callback to return the result.
6425
6426> **NOTE**
6427>
6428> This API is supported since API version 8 and deprecated since API version 13. Use [packToData](#packtodata13) instead.
6429
6430> **NOTE**
6431> If the message "PixelMap mismatch" is returned, the parameters are abnormal. The possible cause is that the PixelMap object is released in advance. You need to check the code and ensure that the PixelMap object is released after this API is called.
6432
6433**Atomic service API**: This API can be used in atomic services since API version 11.
6434
6435**System capability**: SystemCapability.Multimedia.Image.ImagePacker
6436
6437**Parameters**
6438
6439| Name  | Type                           | Mandatory| Description                              |
6440| -------- | ------------------------------- | ---- | ---------------------------------- |
6441| source   | [PixelMap](#pixelmap7)           | Yes  | PixelMap to compress or re-encode.              |
6442| option   | [PackingOption](#packingoption) | Yes  | Encoding parameters.                    |
6443| callback | AsyncCallback\<ArrayBuffer>     | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the compressed or encoded image data; otherwise, **err** is an error object. |
6444
6445**Example**
6446
6447```ts
6448import { BusinessError } from '@kit.BasicServicesKit';
6449
6450const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4.
6451let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
6452image.createPixelMap(color, opts).then((pixelMap: image.PixelMap) => {
6453  let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }
6454  const imagePackerApi: image.ImagePacker = image.createImagePacker();
6455  imagePackerApi.packing(pixelMap, packOpts, (err: BusinessError, data: ArrayBuffer) => {
6456    if (err) {
6457      console.error(`Failed to pack the image.code ${err.code},message is ${err.message}`);
6458    } else {
6459      console.info('Succeeded in packing the image.');
6460    }
6461  })
6462}).catch((error: BusinessError) => {
6463  console.error(`Failed to create the PixelMap.code ${error.code},message is ${error.message}`);
6464})
6465```
6466
6467### packing<sup>(deprecated)</sup>
6468
6469packing(source: PixelMap, option: PackingOption): Promise\<ArrayBuffer>
6470
6471Compresses or re-encodes an image. This API uses a promise to return the result.
6472
6473> **NOTE**
6474>
6475> This API is supported since API version 8 and deprecated since API version 13. Use [packToData](#packtodata13) instead.
6476>
6477> If the message "PixelMap mismatch" is returned, the parameters are abnormal. The possible cause is that the PixelMap object is released in advance. You need to check the code and ensure that the PixelMap object is released after this API is called.
6478
6479**Atomic service API**: This API can be used in atomic services since API version 11.
6480
6481**System capability**: SystemCapability.Multimedia.Image.ImagePacker
6482
6483**Parameters**
6484
6485| Name| Type                           | Mandatory| Description              |
6486| ------ | ------------------------------- | ---- | ------------------ |
6487| source | [PixelMap](#pixelmap7)           | Yes  | PixelMap to compress or re-encode.|
6488| option | [PackingOption](#packingoption) | Yes  | Encoding parameters.    |
6489
6490**Return value**
6491
6492| Type                 | Description                                        |
6493| --------------------- | -------------------------------------------- |
6494| Promise\<ArrayBuffer> | Promise used to return the compressed or encoded image data.|
6495
6496**Example**
6497
6498```ts
6499import { BusinessError } from '@kit.BasicServicesKit';
6500
6501const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4.
6502let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
6503image.createPixelMap(color, opts).then((pixelMap: image.PixelMap) => {
6504  let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }
6505  const imagePackerApi: image.ImagePacker = image.createImagePacker();
6506  imagePackerApi.packing(pixelMap, packOpts)
6507    .then((data: ArrayBuffer) => {
6508      console.info('Succeeded in packing the image.');
6509    }).catch((error: BusinessError) => {
6510    console.error(`Failed to pack the image.code ${error.code},message is ${error.message}`);
6511  })
6512}).catch((error: BusinessError) => {
6513  console.error(`Failed to create PixelMap.code ${error.code},message is ${error.message}`);
6514})
6515```
6516
6517### release
6518
6519release(callback: AsyncCallback\<void>): void
6520
6521Releases this ImagePacker instance. This API uses an asynchronous callback to return the result.
6522
6523ArkTS supports memory reclamation. Even if the application does not call **release()**, the memory of the ImagePacker object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
6524
6525**System capability**: SystemCapability.Multimedia.Image.ImagePacker
6526
6527**Parameters**
6528
6529| Name  | Type                | Mandatory| Description                          |
6530| -------- | -------------------- | ---- | ------------------------------ |
6531| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
6532
6533**Example**
6534
6535```ts
6536import { BusinessError } from '@kit.BasicServicesKit';
6537
6538const imagePackerApi: image.ImagePacker = image.createImagePacker();
6539imagePackerApi.release((err: BusinessError)=>{
6540  if (err) {
6541    console.error(`Failed to release image packaging.code ${err.code},message is ${err.message}`);
6542  } else {
6543    console.info('Succeeded in releasing image packaging.');
6544  }
6545})
6546```
6547
6548### release
6549
6550release(): Promise\<void>
6551
6552Releases this ImagePacker instance. This API uses a promise to return the result.
6553
6554ArkTS supports memory reclamation. Even if the application does not call **release()**, the memory of the ImagePacker object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
6555
6556**System capability**: SystemCapability.Multimedia.Image.ImagePacker
6557
6558**Return value**
6559
6560| Type          | Description                                                  |
6561| -------------- | ------------------------------------------------------ |
6562| Promise\<void> |  Promise that returns no value.|
6563
6564**Example**
6565
6566```ts
6567import { BusinessError } from '@kit.BasicServicesKit';
6568
6569const imagePackerApi: image.ImagePacker = image.createImagePacker();
6570imagePackerApi.release().then(() => {
6571  console.info('Succeeded in releasing image packaging.');
6572}).catch((error: BusinessError) => {
6573  console.error(`Failed to release image packaging.code ${error.code},message is ${error.message}`);
6574})
6575```
6576
6577### packToFile<sup>11+</sup>
6578
6579packToFile(source: ImageSource, fd: number, options: PackingOption, callback: AsyncCallback\<void>): void
6580
6581Encodes the image source into a file based on the specified encoding parameters. This API uses an asynchronous callback to return the result.
6582
6583**System capability**: SystemCapability.Multimedia.Image.ImagePacker
6584
6585**Parameters**
6586
6587| Name  | Type                           | Mandatory| Description                          |
6588| -------- | ------------------------------- | ---- | ------------------------------ |
6589| source   | [ImageSource](#imagesource)     | Yes  | Image source to encode.                |
6590| fd       | number                          | Yes  | File descriptor.                  |
6591| options   | [PackingOption](#packingoption) | Yes  | Encoding parameters.                |
6592| callback | AsyncCallback\<void>            | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. |
6593
6594**Error codes**
6595
6596For details about the error codes, see [Image Error Codes](errorcode-image.md).
6597
6598| ID| Error Message|
6599| ------- | --------------------------------------------|
6600| 62980096| Operation failed.Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.              |
6601| 62980101 | The image data is abnormal. |
6602| 62980106 | The image data is too large. This status code is thrown when an error occurs during the process of checking size. |
6603| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted.            |
6604| 62980115 | Invalid input parameter. |
6605| 62980119 | Failed to encode the image. |
6606| 62980120 | Add pixelmap out of range. |
6607| 62980172 | Failed to encode icc. |
6608| 62980252 | Failed to create surface. |
6609
6610**Example**
6611
6612<!--code_no_check-->
6613```ts
6614import { common } from '@kit.AbilityKit';
6615import { BusinessError } from '@kit.BasicServicesKit';
6616import { fileIo as fs } from '@kit.CoreFileKit';
6617
6618// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
6619let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
6620// 'test.png' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
6621const path: string = context.filesDir + "/test.png";
6622const imageSourceApi: image.ImageSource = image.createImageSource(path);
6623let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 };
6624const filePath: string = context.filesDir + "/image_source.jpg";
6625let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
6626const imagePackerApi: image.ImagePacker = image.createImagePacker();
6627imagePackerApi.packToFile(imageSourceApi, file.fd, packOpts, (err: BusinessError) => {
6628  if (err) {
6629    console.error(`Failed to pack the image to file.code ${err.code},message is ${err.message}`);
6630  } else {
6631    console.info('Succeeded in packing the image to file.');
6632  }
6633})
6634```
6635
6636### packToFile<sup>11+</sup>
6637
6638packToFile (source: ImageSource, fd: number, options: PackingOption): Promise\<void>
6639
6640Encodes the image source into a file based on the specified encoding parameters. This API uses a promise to return the result.
6641
6642**System capability**: SystemCapability.Multimedia.Image.ImagePacker
6643
6644**Parameters**
6645
6646| Name| Type                           | Mandatory| Description          |
6647| ------ | ------------------------------- | ---- | -------------- |
6648| source | [ImageSource](#imagesource)     | Yes  | Image source to encode.|
6649| fd     | number                          | Yes  | File descriptor.  |
6650| options | [PackingOption](#packingoption) | Yes  | Encoding parameters.|
6651
6652**Return value**
6653
6654| Type          | Description                             |
6655| -------------- | --------------------------------- |
6656| Promise\<void> |  Promise that returns no value.|
6657
6658**Error codes**
6659
6660For details about the error codes, see [Image Error Codes](errorcode-image.md).
6661
6662| ID| Error Message|
6663| ------- | --------------------------------------------|
6664| 62980096| Operation failed.Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.              |
6665| 62980101 | The image data is abnormal. |
6666| 62980106 | The image data is too large. This status code is thrown when an error occurs during the process of checking size. |
6667| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted.            |
6668| 62980115 | Invalid input parameter. |
6669| 62980119 | Failed to encode the image. |
6670| 62980120 | Add pixelmap out of range. |
6671| 62980172 | Failed to encode icc. |
6672| 62980252 | Failed to create surface. |
6673
6674**Example**
6675
6676<!--code_no_check-->
6677```ts
6678import { common } from '@kit.AbilityKit';
6679import { BusinessError } from '@kit.BasicServicesKit';
6680import { fileIo as fs } from '@kit.CoreFileKit';
6681
6682// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
6683let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
6684// 'test.png' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
6685const path: string = context.filesDir + "/test.png";
6686const imageSourceApi: image.ImageSource = image.createImageSource(path);
6687let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 };
6688const filePath: string = context.filesDir + "/image_source.jpg";
6689let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
6690const imagePackerApi: image.ImagePacker = image.createImagePacker();
6691imagePackerApi.packToFile(imageSourceApi, file.fd, packOpts).then(() => {
6692  console.info('Succeeded in packing the image to file.');
6693}).catch((error: BusinessError) => {
6694  console.error(`Failed to pack the image to file.code ${error.code},message is ${error.message}`);
6695})
6696```
6697
6698### packToFile<sup>11+</sup>
6699
6700packToFile (source: PixelMap, fd: number, options: PackingOption,  callback: AsyncCallback\<void>): void
6701
6702Encodes the PixelMap into a file based on the specified encoding parameters. This API uses an asynchronous callback to return the result.
6703
6704> **NOTE**
6705> If error code 62980115 is returned, the parameters are abnormal. The possible cause is that the PixelMap object is released in advance. You need to check the code and ensure that the PixelMap object is released after this API is called.
6706
6707**System capability**: SystemCapability.Multimedia.Image.ImagePacker
6708
6709**Parameters**
6710
6711| Name  | Type                           | Mandatory| Description                          |
6712| -------- | ------------------------------- | ---- | ------------------------------ |
6713| source   | [PixelMap](#pixelmap7)          | Yes  | PixelMap to encode.          |
6714| fd       | number                          | Yes  | File descriptor.                  |
6715| options   | [PackingOption](#packingoption) | Yes  | Encoding parameters.                |
6716| callback | AsyncCallback\<void>            | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. |
6717
6718**Error codes**
6719
6720For details about the error codes, see [Image Error Codes](errorcode-image.md).
6721
6722| ID| Error Message|
6723| ------- | --------------------------------------------|
6724| 62980096| Operation failed.Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.              |
6725| 62980101 | The image data is abnormal. |
6726| 62980106 | The image data is too large. This status code is thrown when an error occurs during the process of checking size. |
6727| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted.            |
6728| 62980115 | Invalid input parameter. |
6729| 62980119 | Failed to encode the image. |
6730| 62980120 | Add pixelmap out of range. |
6731| 62980172 | Failed to encode icc. |
6732| 62980252 | Failed to create surface. |
6733
6734**Example**
6735
6736<!--code_no_check-->
6737```ts
6738import { common } from '@kit.AbilityKit';
6739import { BusinessError } from '@kit.BasicServicesKit';
6740import { fileIo as fs } from '@kit.CoreFileKit';
6741
6742const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4.
6743let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
6744// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
6745let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
6746const path: string = context.filesDir + "/pixel_map.jpg";
6747image.createPixelMap(color, opts).then((pixelmap: image.PixelMap) => {
6748  let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }
6749  let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
6750  const imagePackerApi: image.ImagePacker = image.createImagePacker();
6751  imagePackerApi.packToFile(pixelmap, file.fd, packOpts, (err: BusinessError) => {
6752    if (err) {
6753      console.error(`Failed to pack the image to file.code ${err.code},message is ${err.message}`);
6754    } else {
6755      console.info('Succeeded in packing the image to file.');
6756    }
6757  })
6758})
6759```
6760
6761### packToFile<sup>11+</sup>
6762
6763packToFile (source: PixelMap, fd: number, options: PackingOption): Promise\<void>
6764
6765Encodes the PixelMap into a file based on the specified encoding parameters. This API uses a promise to return the result.
6766
6767> **NOTE**
6768> If error code 62980115 is returned, the parameters are abnormal. The possible cause is that the PixelMap object is released in advance. You need to check the code and ensure that the PixelMap object is released after this API is called.
6769
6770**System capability**: SystemCapability.Multimedia.Image.ImagePacker
6771
6772**Parameters**
6773
6774| Name| Type                           | Mandatory| Description                |
6775| ------ | ------------------------------- | ---- | -------------------- |
6776| source | [PixelMap](#pixelmap7)          | Yes  | PixelMap to encode.|
6777| fd     | number                          | Yes  | File descriptor.        |
6778| options | [PackingOption](#packingoption) | Yes  | Encoding parameters.      |
6779
6780**Return value**
6781
6782| Type          | Description                             |
6783| -------------- | --------------------------------- |
6784| Promise\<void> |  Promise that returns no value.|
6785
6786**Error codes**
6787
6788For details about the error codes, see [Image Error Codes](errorcode-image.md).
6789
6790| ID| Error Message|
6791| ------- | --------------------------------------------|
6792| 62980096| Operation failed.Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.              |
6793| 62980101 | The image data is abnormal. |
6794| 62980106 | The image data is too large. This status code is thrown when an error occurs during the process of checking size. |
6795| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted.            |
6796| 62980115 | Invalid input parameter. |
6797| 62980119 | Failed to encode the image. |
6798| 62980120 | Add pixelmap out of range. |
6799| 62980172 | Failed to encode icc. |
6800| 62980252 | Failed to create surface. |
6801
6802**Example**
6803
6804<!--code_no_check-->
6805```ts
6806import { common } from '@kit.AbilityKit';
6807import { BusinessError } from '@kit.BasicServicesKit';
6808import { fileIo as fs } from '@kit.CoreFileKit';
6809
6810const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4.
6811let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
6812// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
6813let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
6814const path: string = context.filesDir + "/pixel_map.jpg";
6815image.createPixelMap(color, opts).then((pixelmap: image.PixelMap) => {
6816  let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }
6817  let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
6818  const imagePackerApi: image.ImagePacker = image.createImagePacker();
6819  imagePackerApi.packToFile(pixelmap, file.fd, packOpts)
6820    .then(() => {
6821      console.info('Succeeded in packing the image to file.');
6822    }).catch((error: BusinessError) => {
6823    console.error(`Failed to pack the image to file.code ${error.code},message is ${error.message}`);
6824  })
6825})
6826```
6827
6828### packToFile<sup>13+</sup>
6829
6830packToFile(picture: Picture, fd: number, options: PackingOption): Promise\<void>
6831
6832Encodes the Picture into a file based on the specified encoding parameters. This API uses a promise to return the result.
6833
6834**System capability**: SystemCapability.Multimedia.Image.ImagePacker
6835
6836**Parameters**
6837
6838| Name | Type                        | Mandatory| Description                |
6839| ------- | ---------------------------- | ---- | -------------------- |
6840| picture  | [Picture](#picture13)          | Yes  | Picture to encode.|
6841| fd      | number                       | Yes  | File descriptor.        |
6842| options | [PackingOption](#packingoption) | Yes  | Encoding parameters.      |
6843
6844**Return value**
6845
6846| Type          | Description                     |
6847| -------------- | ------------------------- |
6848| Promise\<void> | that returns no value.|
6849
6850**Error codes**
6851
6852For details about the error codes, see [Image Error Codes](errorcode-image.md).
6853
6854| ID| Error Message                                                    |
6855| -------- | ------------------------------------------------------------ |
6856| 401      | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
6857| 7800301  | Encode failed.                                         |
6858
6859**Example**
6860
6861```ts
6862import { BusinessError } from '@kit.BasicServicesKit';
6863import { image } from '@kit.ImageKit';
6864import { fileIo as fs } from '@kit.CoreFileKit';
6865
6866async function PackToFile(context: Context) {
6867  const resourceMgr = context.resourceManager;
6868  const rawFile = await resourceMgr.getRawFileContent("test.jpg");
6869  let ops: image.SourceOptions = {
6870    sourceDensity: 98,
6871  }
6872  let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
6873  let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap();
6874  let pictureObj: image.Picture = image.createPicture(commodityPixelMap);
6875
6876  let funcName = "PackToFile";
6877  const imagePackerApi: image.ImagePacker = image.createImagePacker();
6878  if (imagePackerApi != null) {
6879    const filePath: string = context.filesDir + "/test.jpg";
6880    let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
6881    let packOpts: image.PackingOption = {
6882      format: "image/jpeg",
6883      quality: 98,
6884      bufferSize: 10,
6885      desiredDynamicRange: image.PackingDynamicRange.AUTO,
6886      needsPackProperties: true};
6887    await imagePackerApi.packToFile(pictureObj, file.fd, packOpts).then(() => {
6888      console.info(funcName, 'Succeeded in packing the image to file.');
6889    }).catch((error: BusinessError) => {
6890      console.error(funcName, 'Failed to pack the image to file.code ${error.code},message is ${error.message}');
6891    });
6892  }
6893}
6894```
6895
6896### packToFileFromPixelmapSequence<sup>18+</sup>
6897
6898packToFileFromPixelmapSequence(pixelmapSequence: Array\<PixelMap>, fd: number, options: PackingOptionsForSequence): Promise\<void>
6899
6900Encodes multiple PixelMaps into a GIF file. This API uses a promise to return the result.
6901
6902**System capability**: SystemCapability.Multimedia.Image.ImagePacker
6903
6904**Parameters**
6905
6906| Name          | Type                                                     | Mandatory| Description                  |
6907| ---------------- | --------------------------------------------------------- | ---- | ---------------------- |
6908| pixelmapSequence | Array<[PixelMap](#pixelmap7)>                             | Yes  | PixelMaps to encode.|
6909| fd               | number                                                    | Yes  | File descriptor.          |
6910| options          | [PackingOptionsForSequence](#packingoptionsforsequence18) | Yes  | Options for encoding animated images.        |
6911
6912**Return value**
6913
6914| Type          | Description                     |
6915| -------------- | ------------------------- |
6916| Promise\<void> | that returns no value.|
6917
6918**Error codes**
6919
6920For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Image Error Codes](errorcode-image.md).
6921
6922| ID| Error Message                                                    |
6923| -------- | ------------------------------------------------------------ |
6924| 401      | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
6925| 7800201  | Unsupported packing options.                                 |
6926| 7800301  | Failed to encode image.                                      |
6927
6928**Example**
6929
6930<!--code_no_check-->
6931```ts
6932import { common } from '@kit.AbilityKit';
6933import { BusinessError } from '@ohos.base';
6934import fs from '@ohos.file.fs';
6935import image from "@ohos.multimedia.image";
6936
6937// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
6938let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
6939const resourceMgr = context.resourceManager;
6940// 'moving_test.gif' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
6941const fileData = await resourceMgr.getRawFileContent('moving_test.gif');
6942const color = fileData.buffer;
6943let imageSource = image.createImageSource(color);
6944let pixelMapList = await imageSource.createPixelMapList();
6945let path: string = context.cacheDir + '/result.gif';
6946let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
6947let ops: image.PackingOptionsForSequence = {
6948  frameCount: 3, // Set the number of frames in GIF encoding to 3.
6949  delayTimeList: [10, 10, 10], // Set the delay time of three frames in GIF encoding to 100 ms, 100 ms, and 100 ms, respectively.
6950  disposalTypes: [3, 2, 3], // Specify the frame transition modes of the three frames in GIF encoding as 3 (restore to the previous state), 2 (restore to the background color), and 3 (restore to the previous state).
6951  loopCount: 0 // Set the number of loops in GIF encoding to infinite.
6952};
6953let Packer = image.createImagePacker();
6954Packer.packToFileFromPixelmapSequence(pixelMapList, file.fd, ops)
6955  .then(() => {
6956    console.info('Succeeded in packToFileMultiFrames.');
6957  }).catch((error: BusinessError) => {
6958  console.error('Failed to packToFileMultiFrames.');
6959  })
6960```
6961
6962## image.getImagePackerSupportedFormats<sup>20+</sup>
6963
6964getImagePackerSupportedFormats(): string[]
6965
6966Obtains the supported encoding formats, represented by MIME types.
6967
6968**System capability**: SystemCapability.Multimedia.Image.Core
6969
6970**Return value**
6971
6972| Type    | Description                                      |
6973| -------- | ------------------------------------------ |
6974| string[] | List of supported encoding formats (MIME types).|
6975
6976**Example**
6977
6978```ts
6979import { image } from '@kit.ImageKit';
6980function GetImagePackerSupportedFormats() {
6981    let formats = image.getImagePackerSupportedFormats();
6982    console.info('formats:', formats);
6983}
6984```
6985
6986## image.createAuxiliaryPicture<sup>13+</sup>
6987
6988createAuxiliaryPicture(buffer: ArrayBuffer, size: Size, type: AuxiliaryPictureType): AuxiliaryPicture
6989
6990Creates an AuxiliaryPicture instance based on the ArrayBuffer image data, auxiliary picture size, and auxiliary picture type.
6991
6992**System capability**: SystemCapability.Multimedia.Image.Core
6993
6994**Parameters**
6995
6996| Name| Type                                           | Mandatory| Description                        |
6997| ------ | ----------------------------------------------- | ---- | ---------------------------- |
6998| buffer | ArrayBuffer                                     | Yes  | Image data stored in the buffer. |
6999| size   | [Size](#size)                                   | Yes  | Size of the auxiliary picture, in px.   |
7000| type   | [AuxiliaryPictureType](#auxiliarypicturetype13) | Yes  | Type of the auxiliary picture.                |
7001
7002**Return value**
7003
7004| Type                                   | Description                                      |
7005| --------------------------------------- | ------------------------------------------ |
7006| [AuxiliaryPicture](#auxiliarypicture13) | AuxiliaryPicture instance.|
7007
7008**Error codes**
7009
7010For details about the error codes, see [Image Error Codes](errorcode-image.md).
7011
7012| ID| Error Message                                                    |
7013| -------- | ------------------------------------------------------------ |
7014| 401      | Parameter error.Possible causes:1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
7015
7016**Example**
7017
7018```ts
7019import { image } from '@kit.ImageKit';
7020
7021async function CreateAuxiliaryPicture(context: Context) {
7022  let funcName = "CreateAuxiliaryPicture";
7023  const resourceMgr = context.resourceManager;
7024  const rawFile = await resourceMgr.getRawFileContent("hdr.jpg"); // Support for HDR images is required.
7025  let auxBuffer: ArrayBuffer = rawFile.buffer as ArrayBuffer;
7026  let auxSize: Size = {
7027    height: 180,
7028    width: 240
7029  };
7030  let auxType: image.AuxiliaryPictureType = image.AuxiliaryPictureType.GAINMAP;
7031  let auxPictureObj: image.AuxiliaryPicture | null = image.createAuxiliaryPicture(auxBuffer, auxSize, auxType);
7032  if(auxPictureObj != null) {
7033    let type: image.AuxiliaryPictureType = auxPictureObj.getType();
7034    console.info(funcName, 'CreateAuxiliaryPicture succeeded this.Aux_picture.type.' + JSON.stringify(type));
7035  } else {
7036    console.error(funcName, 'CreateAuxiliaryPicture failed');
7037  }
7038}
7039```
7040
7041## AuxiliaryPicture<sup>13+</sup>
7042
7043The auxiliary picture is generally used to assist the main picture in displaying special information, so that the image includes richer information. The **AuxiliaryPicture** class is used to read or write auxiliary picture data of an image and obtain auxiliary picture information of an image. Before calling any API in AuxiliaryPicture, you must use [createAuxiliaryPicture](#imagecreateauxiliarypicture13) to create an AuxiliaryPicture object.
7044
7045### Properties
7046
7047**System capability**: SystemCapability.Multimedia.Image.Core
7048
7049### writePixelsFromBuffer<sup>13+</sup>
7050
7051writePixelsFromBuffer(data: ArrayBuffer): Promise\<void>
7052
7053Reads pixels from an ArrayBuffer and writes the data to this AuxiliaryPicture object. This API uses a promise to return the result.
7054
7055**System capability**: SystemCapability.Multimedia.Image.Core
7056
7057**Parameters**
7058
7059| Name| Type       | Mandatory| Description            |
7060| ------ | ----------- | ---- | ---------------- |
7061| data   | ArrayBuffer | Yes  | Pixels of the auxiliary picture.|
7062
7063**Return value**
7064
7065| Type          | Description                                  |
7066| -------------- | -------------------------------------- |
7067| Promise\<void> | Promise that returns no value.|
7068
7069**Error codes**
7070
7071For details about the error codes, see [Image Error Codes](errorcode-image.md).
7072
7073| ID| Error Message                                                    |
7074| -------- | ------------------------------------------------------------ |
7075| 401      | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
7076| 7600301  | Memory alloc failed.                                         |
7077| 7600302  | Memory copy failed.                                          |
7078
7079**Example**
7080
7081```ts
7082import { image } from '@kit.ImageKit';
7083
7084async function WritePixelsFromBuffer(context: Context) {
7085  const resourceMgr = context.resourceManager;
7086  const rawFile = await resourceMgr.getRawFileContent("hdr.jpg"); // Support for HDR images is required.
7087  let ops: image.SourceOptions = {
7088    sourceDensity: 98,
7089  }
7090  let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
7091  let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap();
7092  let pictureObj: image.Picture = image.createPicture(commodityPixelMap);
7093  let auxPictureObj: image.AuxiliaryPicture | null = pictureObj.getAuxiliaryPicture(image.AuxiliaryPictureType.GAINMAP);
7094  if(auxPictureObj != null) {
7095    let auxBuffer: ArrayBuffer = await auxPictureObj.readPixelsToBuffer();
7096    await auxPictureObj.writePixelsFromBuffer(auxBuffer);
7097    console.info('Write pixels from buffer success.');
7098  } else {
7099    console.error('AuxPictureObj is null.');
7100  }
7101}
7102```
7103
7104### readPixelsToBuffer<sup>13+</sup>
7105
7106readPixelsToBuffer(): Promise\<ArrayBuffer>
7107
7108Reads pixels of this auxiliary picture and writes the data to an ArrayBuffer. This API uses a promise to return the result.
7109
7110**System capability**: SystemCapability.Multimedia.Image.Core
7111
7112**Return value**
7113
7114| Type                 | Description                             |
7115| --------------------- | --------------------------------- |
7116| Promise\<ArrayBuffer> | Promise used to return the pixels of the auxiliary picture.|
7117
7118**Error codes**
7119
7120For details about the error codes, see [Image Error Codes](errorcode-image.md).
7121
7122| ID| Error Message            |
7123| -------- | -------------------- |
7124| 7600301  | Memory alloc failed. |
7125| 7600302  | Memory copy failed.  |
7126
7127**Example**
7128
7129```ts
7130import { BusinessError } from '@kit.BasicServicesKit';
7131import { image } from '@kit.ImageKit';
7132
7133async function ReadPixelsToBuffer(context: Context) {
7134  const resourceMgr = context.resourceManager;
7135  const rawFile = await resourceMgr.getRawFileContent("hdr.jpg"); // Support for HDR images is required.
7136  let ops: image.SourceOptions = {
7137    sourceDensity: 98,
7138  }
7139  let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
7140  let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap();
7141  let pictureObj: image.Picture = image.createPicture(commodityPixelMap);
7142  let auxPictureObj: image.AuxiliaryPicture | null = pictureObj.getAuxiliaryPicture(image.AuxiliaryPictureType.GAINMAP);
7143  if(auxPictureObj != null) {
7144    await auxPictureObj.readPixelsToBuffer().then((pixelsBuffer: ArrayBuffer) => {
7145      console.info('Read pixels to buffer success.' );
7146    }).catch((error: BusinessError) => {
7147      console.error('Read pixels to buffer failed error.code: ' + JSON.stringify(error.code) + ' ,error.message:' + JSON.stringify(error.message));
7148    });
7149  } else {
7150    console.error('AuxPictureObj is null.');
7151  }
7152}
7153```
7154
7155### getType<sup>13+</sup>
7156
7157getType(): AuxiliaryPictureType
7158
7159Obtains the type of this auxiliary picture.
7160
7161**System capability**: SystemCapability.Multimedia.Image.Core
7162
7163**Return value**
7164
7165| Type                                           | Description                        |
7166| ----------------------------------------------- | ---------------------------- |
7167| [AuxiliaryPictureType](#auxiliarypicturetype13) | Type of the auxiliary picture.|
7168
7169**Example**
7170
7171```ts
7172import { image } from '@kit.ImageKit';
7173
7174async function GetAuxiliaryPictureType() {
7175  if (auxPictureObj != null) {
7176    let type: image.AuxiliaryPictureType = auxPictureObj.getType();
7177    console.info('Success get auxiliary picture type ' +  JSON.stringify(type));
7178  } else {
7179    console.error('Failed get auxiliary picture type ');
7180  }
7181}
7182```
7183
7184### setMetadata<sup>13+</sup>
7185
7186setMetadata(metadataType: MetadataType, metadata: Metadata): Promise\<void>
7187
7188Sets the metadata for this auxiliary picture.
7189
7190**System capability**: SystemCapability.Multimedia.Image.Core
7191
7192**Parameters**
7193
7194| Name      | Type                           | Mandatory| Description                                |
7195| ------------ | ------------------------------- | ---- | ------------------------------------ |
7196| metadataType | [MetadataType](#metadatatype13) | Yes  | Metadata type, which is used to set the corresponding metadata.|
7197| metadata     | [Metadata](#metadata13)         | Yes  | Metadata object.                        |
7198
7199**Return value**
7200
7201| Type          | Description                                  |
7202| -------------- | -------------------------------------- |
7203| Promise\<void> | Promise that returns no value.|
7204
7205**Error codes**
7206
7207For details about the error codes, see [Image Error Codes](errorcode-image.md).
7208
7209| ID| Error Message                                                    |
7210| -------- | ------------------------------------------------------------ |
7211| 401      | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
7212| 7600202  | Unsupported metadata. Possible causes: 1. Unsupported metadata type. 2. The metadata type does not match the auxiliary picture type. |
7213
7214**Example**
7215
7216```ts
7217import { BusinessError } from '@kit.BasicServicesKit';
7218import { image } from '@kit.ImageKit';
7219
7220async function SetAuxPictureObjMetadata(exifContext: Context) {
7221  const exifResourceMgr = exifContext.resourceManager;
7222  const exifRawFile = await exifResourceMgr.getRawFileContent("exif.jpg");// The image contains EXIF metadata.
7223  let exifOps: image.SourceOptions = {
7224    sourceDensity: 98,
7225  }
7226  let exifImageSource: image.ImageSource = image.createImageSource(exifRawFile.buffer as ArrayBuffer, exifOps);
7227  let exifCommodityPixelMap: image.PixelMap = await exifImageSource.createPixelMap();
7228  let exifPictureObj: image.Picture = image.createPicture(exifCommodityPixelMap);
7229  if (exifPictureObj != null) {
7230    console.info('Create picture succeeded');
7231  } else {
7232    console.error('Create picture failed');
7233  }
7234
7235  if (auxPictureObj != null) {
7236    let metadataType: image.MetadataType = image.MetadataType.EXIF_METADATA;
7237    let exifMetaData: image.Metadata = await exifPictureObj.getMetadata(metadataType);
7238    auxPictureObj.setMetadata(metadataType, exifMetaData).then(() => {
7239      console.info('Set metadata success');
7240    }).catch((error: BusinessError) => {
7241      console.error('Set metadata failed.error.code: ${error.code}, error.message: ${error.message}');
7242    });
7243  } else {
7244    console.error('AuxPictureObjMetaData is null');
7245  }
7246}
7247```
7248
7249### getMetadata<sup>13+</sup>
7250
7251getMetadata(metadataType: MetadataType): Promise\<Metadata>
7252
7253Obtains the metadata of this auxiliary picture.
7254
7255**System capability**: SystemCapability.Multimedia.Image.Core
7256
7257**Parameters**
7258
7259| Name      | Type                           | Mandatory| Description                                  |
7260| ------------ | ------------------------------- | ---- | -------------------------------------- |
7261| metadataType | [MetadataType](#metadatatype13) | Yes  | Metadata type, which is used to obtain metadata of the corresponding type.|
7262
7263**Return value**
7264
7265| Type                            | Description            |
7266| -------------------------------- | ---------------- |
7267| Promise<[Metadata](#metadata13)> | Metadata object.|
7268
7269**Error codes**
7270
7271For details about the error codes, see [Image Error Codes](errorcode-image.md).
7272
7273| ID| Error Message                                                    |
7274| -------- | ------------------------------------------------------------ |
7275| 401      | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
7276| 7600202  | Unsupported metadata. Possible causes: 1. Unsupported metadata type. 2. The metadata type does not match the auxiliary picture type. |
7277
7278**Example**
7279
7280```ts
7281import { image } from '@kit.ImageKit';
7282
7283async function GetAuxPictureObjMetadata() {
7284  if (auxPictureObj != null) {
7285    let metadataType: image.MetadataType = image.MetadataType.EXIF_METADATA;
7286    let auxPictureObjMetaData: image.Metadata | null = await auxPictureObj.getMetadata(metadataType);
7287    if (auxPictureObjMetaData != null) {
7288      console.info('Get auxpictureobj Metadata success' );
7289    } else {
7290      console.error('Get auxpictureobj Metadata failed');
7291    }
7292  } else {
7293    console.error('Get auxpictureobj is null.');
7294  }
7295}
7296```
7297
7298### getAuxiliaryPictureinfo<sup>13+</sup>
7299
7300getAuxiliaryPictureInfo(): AuxiliaryPictureInfo
7301
7302Obtains the auxiliary picture information.
7303
7304**System capability**: SystemCapability.Multimedia.Image.Core
7305
7306**Return value**
7307
7308| Type                                           | Description                             |
7309| ----------------------------------------------- | --------------------------------- |
7310| [AuxiliaryPictureInfo](#auxiliarypictureinfo13) | Promise used to return the auxiliary picture information.|
7311
7312**Example**
7313
7314```ts
7315import { image } from '@kit.ImageKit';
7316
7317async function GetAuxiliaryPictureInfo() {
7318  if(auxPictureObj != null) {
7319    let auxinfo: image.AuxiliaryPictureInfo = auxPictureObj.getAuxiliaryPictureInfo();
7320    console.info('GetAuxiliaryPictureInfo Type: ' + auxinfo.auxiliaryPictureType +
7321      ' height: ' + auxinfo.size.height + ' width: ' + auxinfo.size.width +
7322      ' rowStride: ' +  auxinfo.rowStride +  ' pixelFormat: ' + auxinfo.pixelFormat +
7323      ' colorSpace: ' +  auxinfo.colorSpace);
7324  } else {
7325    console.error('Get auxiliary picture information failed');
7326  }
7327}
7328```
7329
7330### setAuxiliaryPictureinfo<sup>13+</sup>
7331
7332setAuxiliaryPictureInfo(info: AuxiliaryPictureInfo): void
7333
7334Sets the auxiliary picture information.
7335
7336**System capability**: SystemCapability.Multimedia.Image.Core
7337
7338**Parameters**
7339
7340| Name| Type                                           | Mandatory| Description              |
7341| ------ | ----------------------------------------------- | ---- | ------------------ |
7342| info   | [AuxiliaryPictureInfo](#auxiliarypictureinfo13) | Yes  | Auxiliary picture information.|
7343
7344**Error codes**
7345
7346For details about the error codes, see [Image Error Codes](errorcode-image.md).
7347
7348| ID| Error Message                                                    |
7349| -------- | :----------------------------------------------------------- |
7350| 401      | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
7351
7352**Example**
7353
7354```ts
7355import { colorSpaceManager } from '@kit.ArkGraphics2D';
7356import { image } from '@kit.ImageKit';
7357
7358async function SetAuxiliaryPictureInfo() {
7359  if(auxPictureObj != null) {
7360    let colorSpaceName = colorSpaceManager.ColorSpace.SRGB;
7361    let info: image.AuxiliaryPictureInfo = {
7362      auxiliaryPictureType: image.AuxiliaryPictureType.GAINMAP,
7363      size: {height: 100, width: 200},
7364      pixelFormat: image.PixelMapFormat.RGBA_8888,
7365      rowStride: 0,
7366      colorSpace: colorSpaceManager.create(colorSpaceName),
7367    };
7368    auxPictureObj.setAuxiliaryPictureInfo(info);
7369  }
7370}
7371```
7372
7373### release<sup>13+</sup>
7374
7375release():void
7376
7377Releases this AuxiliaryPicture object. No value is returned.
7378
7379**System capability**: SystemCapability.Multimedia.Image.Core
7380
7381**Example**
7382
7383```ts
7384import { image } from '@kit.ImageKit';
7385
7386async function Release() {
7387  let funcName = "Release";
7388  if (auxPictureObj != null) {
7389    auxPictureObj.release();
7390    if (auxPictureObj.getType() == null) {
7391      console.info(funcName, 'Success !');
7392    } else {
7393      console.error(funcName, 'Failed !');
7394    }
7395  } else {
7396    console.error('PictureObj is null');
7397  }
7398}
7399```
7400
7401## Metadata<sup>13+</sup>
7402
7403A class used to store image metadata. For details about the supported metadata types, see [MetadataType](#metadatatype13).
7404
7405### Properties
7406
7407**System capability**: SystemCapability.Multimedia.Image.Core
7408
7409### getProperties<sup>13+</sup>
7410
7411getProperties(key: Array\<string>): Promise\<Record\<string, string | null>>
7412
7413Obtains the values of properties from the image's metadata. This API uses a promise to return the result. For details about how to obtain the property values, see [PropertyKey](#propertykey7) and [FragmentMapPropertyKey](#fragmentmappropertykey13).
7414
7415**System capability**: SystemCapability.Multimedia.Image.Core
7416
7417**Parameters**
7418
7419| Name| Type          | Mandatory| Description                    |
7420| ------ | -------------- | ---- | ------------------------ |
7421| key    | Array\<string> | Yes  | Names of the properties.|
7422
7423**Return value**
7424
7425| Type                                    | Description                                                        |
7426| ---------------------------------------- | ------------------------------------------------------------ |
7427| Promise\<Record<string, string \| null>> | Promise used to return the property values. If the retrieval operation fails, an error code is returned.|
7428
7429**Error codes**
7430
7431For details about the error codes, see [Image Error Codes](errorcode-image.md).
7432
7433| ID| Error Message                                                    |
7434| -------- | ------------------------------------------------------------ |
7435| 401      | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types;3.Parameter verification failed; |
7436| 7600202  | Unsupported metadata. Possible causes: 1. Unsupported metadata type. 2. The metadata type does not match the auxiliary picture type. |
7437
7438**Example**
7439
7440```ts
7441import { BusinessError } from '@kit.BasicServicesKit';
7442import { image } from '@kit.ImageKit';
7443
7444async function GetProperties(context: Context) {
7445  const resourceMgr = context.resourceManager;
7446  const rawFile = await resourceMgr.getRawFileContent("exif.jpg"); // The image contains EXIF metadata.
7447  let ops: image.SourceOptions = {
7448    sourceDensity: 98,
7449  }
7450  let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
7451  let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap();
7452  let pictureObj: image.Picture = image.createPicture(commodityPixelMap);
7453  let metadataType: image.MetadataType = image.MetadataType.EXIF_METADATA;
7454  let metaData: image.Metadata | null = await pictureObj.getMetadata(metadataType);
7455  if (metaData != null) {
7456    await metaData.getProperties(["ImageWidth", "ImageLength"]).then((data2) => {
7457      console.info('Get properties ',JSON.stringify(data2));
7458    }).catch((error: BusinessError) => {
7459      console.error('Get properties failed error.code: ' +JSON.stringify(error.code) + ' ,error.message:' + JSON.stringify(error.message));
7460    });
7461  } else {
7462    console.error('Metadata is null.');
7463  }
7464}
7465```
7466
7467### setProperties<sup>13+</sup>
7468
7469setProperties(records: Record\<string, string | null>): Promise\<void>
7470
7471Sets the values of properties for the image's metadata. This API uses a promise to return the result. For details about how to obtain the property values, see [PropertyKey](#propertykey7) and [FragmentMapPropertyKey](#fragmentmappropertykey13).
7472
7473**System capability**: SystemCapability.Multimedia.Image.Core
7474
7475**Parameters**
7476
7477| Name | Type                          | Mandatory| Description                    |
7478| ------- | ------------------------------ | ---- | ------------------------ |
7479| records | Record<string, string \| null> | Yes  | Array of properties and their values.|
7480
7481**Return value**
7482
7483| Type          | Description                                 |
7484| -------------- | ------------------------------------- |
7485| Promise\<void> | Promise that returns no value. If the operation fails, an error code is returned.|
7486
7487**Error codes**
7488
7489For details about the error codes, see [Image Error Codes](errorcode-image.md).
7490
7491| ID| Error Message                                                    |
7492| -------- | ------------------------------------------------------------ |
7493| 401      | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types;3.Parameter verification failed; |
7494| 7600202  | Unsupported metadata. Possible causes: 1. Unsupported metadata type. 2. The metadata type does not match the auxiliary picture type. |
7495
7496**Example**
7497
7498```ts
7499import { BusinessError } from '@kit.BasicServicesKit';
7500import { image } from '@kit.ImageKit';
7501
7502async function SetProperties(context: Context) {
7503  const resourceMgr = context.resourceManager;
7504  const rawFile = await resourceMgr.getRawFileContent("exif.jpg"); // The image contains EXIF metadata.
7505  let ops: image.SourceOptions = {
7506    sourceDensity: 98,
7507  }
7508  let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
7509  let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap();
7510  let pictureObj: image.Picture = image.createPicture(commodityPixelMap);
7511  let metadataType: image.MetadataType = image.MetadataType.EXIF_METADATA;
7512  let metaData: image.Metadata | null = await pictureObj.getMetadata(metadataType);
7513  if (metaData != null) {
7514    let setkey: Record<string, string | null> = {
7515      "ImageWidth": "200",
7516      "ImageLength": "300"
7517    };
7518    await metaData.setProperties(setkey).then(async () => {
7519      console.info('Set auxpictureobj properties success.');
7520    }).catch((error: BusinessError) => {
7521      console.error('Failed to set metadata Properties. code is ${error.code}, message is ${error.message}');
7522    })
7523  } else {
7524    console.error('AuxPictureObj metadata is null. ');
7525  }
7526}
7527```
7528
7529### getAllProperties<sup>13+</sup>
7530
7531getAllProperties(): Promise\<Record<string, string | null>>
7532
7533Obtains all properties and values from the image's metadata. This API uses a promise to return the result. For details about how to obtain the property values, see [PropertyKey](#propertykey7) and [FragmentMapPropertyKey](#fragmentmappropertykey13).
7534
7535**System capability**: SystemCapability.Multimedia.Image.Core
7536
7537**Return value**
7538
7539| Type                                    | Description                                       |
7540| ---------------------------------------- | ------------------------------------------- |
7541| Promise\<Record<string, string \| null>> | Promise used to return the values of all properties.|
7542
7543**Example**
7544
7545```ts
7546import { BusinessError } from '@kit.BasicServicesKit';
7547import { image } from '@kit.ImageKit';
7548
7549async function GetAllProperties(context: Context) {
7550  const resourceMgr = context.resourceManager;
7551  const rawFile = await resourceMgr.getRawFileContent("exif.jpg"); // The image contains EXIF metadata.
7552  let ops: image.SourceOptions = {
7553    sourceDensity: 98,
7554  }
7555  let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
7556  let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap();
7557  let pictureObj: image.Picture = image.createPicture(commodityPixelMap);
7558  let metadataType: image.MetadataType = image.MetadataType.EXIF_METADATA;
7559  let metaData: image.Metadata | null = await pictureObj.getMetadata(metadataType);
7560  if (metaData != null) {
7561    await metaData.getAllProperties().then((data2) => {
7562      const count = Object.keys(data2).length;
7563      console.info('Metadata have ', count, ' properties');
7564      console.info('Get metadata all properties: ', JSON.stringify(data2));
7565    }).catch((error: BusinessError) => {
7566      console.error('Get metadata all properties failed error.code: ' +JSON.stringify(error.code) + ' ,error.message:' + JSON.stringify(error.message));
7567    });
7568  } else {
7569    console.error('Metadata is null.');
7570  }
7571}
7572```
7573
7574### clone<sup>13+</sup>
7575
7576clone(): Promise\<Metadata>
7577
7578Clones the metadata. This API uses a promise to return the result.
7579
7580**System capability**: SystemCapability.Multimedia.Image.Core
7581
7582**Return value**
7583
7584| Type                             | Description                             |
7585| --------------------------------- | --------------------------------- |
7586| Promise\<[Metadata](#metadata13)> | Promise used to return the metadata instance.|
7587
7588**Error codes**
7589
7590For details about the error codes, see [Image Error Codes](errorcode-image.md).
7591
7592| ID| Error Message            |
7593| -------- | -------------------- |
7594| 7600301  | Memory alloc failed. |
7595| 7600302  | Memory copy failed.  |
7596
7597**Example**
7598
7599```ts
7600import { BusinessError } from '@kit.BasicServicesKit';
7601import { image } from '@kit.ImageKit';
7602
7603async function clone(context: Context) {
7604  const resourceMgr = context.resourceManager;
7605  const rawFile = await resourceMgr.getRawFileContent("exif.jpg"); // The image contains EXIF metadata.
7606  let ops: image.SourceOptions = {
7607    sourceDensity: 98,
7608  }
7609  let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
7610  let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap();
7611  let pictureObj: image.Picture = image.createPicture(commodityPixelMap);
7612  let metadataType: image.MetadataType = image.MetadataType.EXIF_METADATA;
7613  let metaData: image.Metadata | null = await pictureObj.getMetadata(metadataType);
7614  if (metaData != null) {
7615    let new_metadata: image.Metadata = await metaData.clone();
7616    new_metadata.getProperties(["ImageWidth"]).then((data1) => {
7617      console.info('Clone new_metadata and get Properties.', JSON.stringify(data1));
7618    }).catch((err: BusinessError) => {
7619      console.error('Clone new_metadata failed.', JSON.stringify(err));
7620    });
7621  } else {
7622    console.error('Metadata is null.');
7623  }
7624}
7625```
7626
7627## image.createImageReceiver<sup>11+</sup>
7628
7629createImageReceiver(size: Size, format: ImageFormat, capacity: number): ImageReceiver
7630
7631Creates an ImageReceiver instance by specifying the image size, format, and capacity. The ImageReceiver acts as the receiver and consumer of images. Its parameter properties do not actually affect the received images. The configuration of image properties should be done on the sending side (the producer), such as when creating a camera preview stream with [createPreviewOutput](../apis-camera-kit/arkts-apis-camera-CameraManager.md#createpreviewoutput).
7632
7633**System capability**: SystemCapability.Multimedia.Image.ImageReceiver
7634
7635**Parameters**
7636
7637| Name  | Type  | Mandatory| Description                  |
7638| -------- | ------ | ---- | ---------------------- |
7639| size    | [Size](#size)  | Yes  | Default size of the image. This parameter does not affect the size of the received image. The actual returned size is determined by the producer, for example, the camera.      |
7640| format   | [ImageFormat](#imageformat9) | Yes  | Image format, which is a constant of [ImageFormat](#imageformat9). (Currently, only **ImageFormat:JPEG** is supported. The format actually returned is determined by the producer, for example, camera.)            |
7641| capacity | number | Yes  | Maximum number of images that can be accessed at the same time.|
7642
7643**Return value**
7644
7645| Type                            | Description                                   |
7646| -------------------------------- | --------------------------------------- |
7647| [ImageReceiver](#imagereceiver9) | ImageReceiver instance.|
7648
7649**Error codes**
7650
7651For details about the error codes, see [Image Error Codes](errorcode-image.md).
7652
7653| ID| Error Message|
7654| ------- | --------------------------------------------|
7655| 401| Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types;   |
7656
7657**Example**
7658
7659```ts
7660let size: image.Size = {
7661  height: 8192,
7662  width: 8
7663}
7664let receiver: image.ImageReceiver = image.createImageReceiver(size, image.ImageFormat.JPEG, 8);
7665```
7666
7667## image.createImageReceiver<sup>(deprecated)</sup>
7668
7669createImageReceiver(width: number, height: number, format: number, capacity: number): ImageReceiver
7670
7671Creates an ImageReceiver instance by specifying the image width, height, format, and capacity. The ImageReceiver acts as the receiver and consumer of images. Its parameter properties do not actually affect the received images. The configuration of image properties should be done on the sending side (the producer), such as when creating a camera preview stream with [createPreviewOutput](../apis-camera-kit/arkts-apis-camera-CameraManager.md#createpreviewoutput).
7672
7673> **NOTE**
7674>
7675> This API is deprecated since API version 11. You are advised to use [createImageReceiver](#imagecreateimagereceiver11).
7676
7677**System capability**: SystemCapability.Multimedia.Image.ImageReceiver
7678
7679**Parameters**
7680
7681| Name  | Type  | Mandatory| Description                  |
7682| -------- | ------ | ---- | ---------------------- |
7683| width    | number | Yes  | Default image width, in px. This parameter does not affect the width of the received image. The actual width is determined by the producer, for example, the camera.      |
7684| height   | number | Yes  | Default image height, in px. This parameter does not affect the height of the received image. The actual height is determined by the producer, for example, the camera.      |
7685| format   | number | Yes  | Image format, which is a constant of [ImageFormat](#imageformat9). (Currently, only **ImageFormat:JPEG** is supported. The format actually returned is determined by the producer, for example, camera.) |
7686| capacity | number | Yes  | Maximum number of images that can be accessed at the same time.|
7687
7688**Return value**
7689
7690| Type                            | Description                                   |
7691| -------------------------------- | --------------------------------------- |
7692| [ImageReceiver](#imagereceiver9) | ImageReceiver instance.|
7693
7694**Example**
7695
7696```ts
7697let receiver: image.ImageReceiver = image.createImageReceiver(8192, 8, image.ImageFormat.JPEG, 8);
7698```
7699
7700## ImageReceiver<sup>9+</sup>
7701
7702Provides APIs to obtain the surface ID of a component, read the latest image, read the next image, and release the ImageReceiver instance. The ImageReceiver acts as the receiver and consumer of images. Its parameter properties do not actually affect the received images. The configuration of image properties should be done on the sending side (the producer), such as when creating a camera preview stream with [createPreviewOutput](../apis-camera-kit/arkts-apis-camera-CameraManager.md#createpreviewoutput).
7703
7704Before calling any APIs in ImageReceiver, you must create an ImageReceiver instance.
7705
7706### Properties
7707
7708**System capability**: SystemCapability.Multimedia.Image.ImageReceiver
7709
7710| Name    | Type                        | Read Only| Optional| Description              |
7711| -------- | ---------------------------- | ---- | ---- | ------------------ |
7712| size     | [Size](#size)                | Yes  | No  | Image size. This parameter does not affect the size of the received image. The actual returned size is determined by the producer, for example, the camera.        |
7713| capacity | number                       | Yes  | No  | Maximum number of images that can be accessed at the same time.|
7714| format   | [ImageFormat](#imageformat9) | Yes  | No  | Image format, which is a constant of [ImageFormat](#imageformat9). (Currently, only **ImageFormat:JPEG** is supported. The format actually returned is determined by the producer, for example, camera.)       |
7715
7716### getReceivingSurfaceId<sup>9+</sup>
7717
7718getReceivingSurfaceId(callback: AsyncCallback\<string>): void
7719
7720Obtains a surface ID for the camera or other components. This API uses an asynchronous callback to return the result.
7721
7722**System capability**: SystemCapability.Multimedia.Image.ImageReceiver
7723
7724**Parameters**
7725
7726| Name  | Type                  | Mandatory| Description                      |
7727| -------- | ---------------------- | ---- | -------------------------- |
7728| callback | AsyncCallback\<string> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the surface ID obtained. Otherwise, **err** is an error object.|
7729
7730**Example**
7731
7732```ts
7733import { BusinessError } from '@kit.BasicServicesKit';
7734
7735receiver.getReceivingSurfaceId((err: BusinessError, id: string) => {
7736  if (err) {
7737    console.error(`Failed to get the ReceivingSurfaceId.code ${err.code},message is ${err.message}`);
7738  } else {
7739    console.info('Succeeded in getting the ReceivingSurfaceId.');
7740  }
7741});
7742```
7743
7744### getReceivingSurfaceId<sup>9+</sup>
7745
7746getReceivingSurfaceId(): Promise\<string>
7747
7748Obtains a surface ID for the camera or other components. This API uses a promise to return the result.
7749
7750**System capability**: SystemCapability.Multimedia.Image.ImageReceiver
7751
7752**Return value**
7753
7754| Type            | Description                |
7755| ---------------- | -------------------- |
7756| Promise\<string> | Promise used to return the surface ID.|
7757
7758**Example**
7759
7760```ts
7761import { BusinessError } from '@kit.BasicServicesKit';
7762
7763receiver.getReceivingSurfaceId().then((id: string) => {
7764  console.info('Succeeded in getting the ReceivingSurfaceId.');
7765}).catch((error: BusinessError) => {
7766  console.error(`Failed to get the ReceivingSurfaceId.code ${error.code},message is ${error.message}`);
7767})
7768```
7769
7770### readLatestImage<sup>9+</sup>
7771
7772readLatestImage(callback: AsyncCallback\<Image>): void
7773
7774Reads the latest image from the ImageReceiver instance. This API uses an asynchronous callback to return the result.
7775
7776**NOTE**: This API can be called to receive data only after the [on](#on9) callback is triggered. When the [Image](#image9) object returned by this API is no longer needed, call [release](#release9-4) to release the object. New data can be received only after the release.
7777
7778**System capability**: SystemCapability.Multimedia.Image.ImageReceiver
7779
7780**Parameters**
7781
7782| Name    | Type                           | Mandatory| Description                    |
7783| -------- | ------------------------------- | ---- | ------------------------ |
7784| callback | AsyncCallback<[Image](#image9)> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the latest image obtained; otherwise, **err** is an error object. |
7785
7786**Example**
7787
7788```ts
7789import { BusinessError } from '@kit.BasicServicesKit';
7790
7791receiver.readLatestImage((err: BusinessError, img: image.Image) => {
7792  if (err) {
7793    console.error(`Failed to read the latest Image.code ${err.code},message is ${err.message}`);
7794  } else {
7795    console.info('Succeeded in reading the latest Image.');
7796  }
7797});
7798```
7799
7800### readLatestImage<sup>9+</sup>
7801
7802readLatestImage(): Promise\<Image>
7803
7804Reads the latest image from the ImageReceiver instance. This API uses a promise to return the result.
7805
7806**NOTE**: This API can be called to receive data only after the [on](#on9) callback is triggered. When the [Image](#image9) object returned by this API is no longer needed, call [release](#release9-4) to release the object. New data can be received only after the release.
7807
7808**System capability**: SystemCapability.Multimedia.Image.ImageReceiver
7809
7810**Return value**
7811
7812| Type                     | Description              |
7813| ------------------------- | ------------------ |
7814| Promise<[Image](#image9)> | Promise used to return the latest image.|
7815
7816**Example**
7817
7818```ts
7819import { BusinessError } from '@kit.BasicServicesKit';
7820
7821receiver.readLatestImage().then((img: image.Image) => {
7822  console.info('Succeeded in reading the latest Image.');
7823}).catch((error: BusinessError) => {
7824  console.error(`Failed to read the latest Image.code ${error.code},message is ${error.message}`);
7825})
7826```
7827
7828### readNextImage<sup>9+</sup>
7829
7830readNextImage(callback: AsyncCallback\<Image>): void
7831
7832Reads the next image from the ImageReceiver instance. This API uses an asynchronous callback to return the result.
7833
7834**NOTE**: This API can be called to receive data only after the [on](#on9) callback is triggered. When the [Image](#image9) object returned by this API is no longer needed, call [release](#release9-4) to release the object. New data can be received only after the release.
7835
7836**System capability**: SystemCapability.Multimedia.Image.ImageReceiver
7837
7838**Parameters**
7839
7840| Name  | Type                           | Mandatory| Description                      |
7841| -------- | ------------------------------- | ---- | -------------------------- |
7842| callback | AsyncCallback<[Image](#image9)> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the next image obtained. Otherwise, **err** is an error object. |
7843
7844**Example**
7845
7846```ts
7847import { BusinessError } from '@kit.BasicServicesKit';
7848
7849receiver.readNextImage((err: BusinessError, img: image.Image) => {
7850  if (err) {
7851    console.error(`Failed to read the next Image.code ${err.code},message is ${err.message}`);
7852  } else {
7853    console.info('Succeeded in reading the next Image.');
7854  }
7855});
7856```
7857
7858### readNextImage<sup>9+</sup>
7859
7860readNextImage(): Promise\<Image>
7861
7862Reads the next image from the ImageReceiver instance. This API uses a promise to return the result.
7863
7864**NOTE**: This API can be called to receive data only after the [on](#on9) callback is triggered. When the [Image](#image9) object returned by this API is no longer needed, call [release](#release9-4) to release the object. New data can be received only after the release.
7865
7866**System capability**: SystemCapability.Multimedia.Image.ImageReceiver
7867
7868**Return value**
7869
7870| Type                     | Description                |
7871| ------------------------- | -------------------- |
7872| Promise<[Image](#image9)> | Promise used to return the next image.|
7873
7874**Example**
7875
7876```ts
7877import { BusinessError } from '@kit.BasicServicesKit';
7878
7879receiver.readNextImage().then((img: image.Image) => {
7880  console.info('Succeeded in reading the next Image.');
7881}).catch((error: BusinessError) => {
7882  console.error(`Failed to read the next Image.code ${error.code},message is ${error.message}`);
7883})
7884```
7885
7886### on<sup>9+</sup>
7887
7888on(type: 'imageArrival', callback: AsyncCallback\<void>): void
7889
7890Listens for image arrival events.
7891
7892**System capability**: SystemCapability.Multimedia.Image.ImageReceiver
7893
7894**Parameters**
7895
7896| Name  | Type                | Mandatory| Description                                                  |
7897| -------- | -------------------- | ---- | ------------------------------------------------------ |
7898| type     | string               | Yes  | Type of event to listen for. The value is fixed at **'imageArrival'**, which is triggered when an image is received.|
7899| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.                                       |
7900
7901**Example**
7902
7903```ts
7904receiver.on('imageArrival', () => {
7905  // image arrival, do something.
7906})
7907```
7908
7909### off<sup>13+</sup>
7910
7911off(type: 'imageArrival', callback?: AsyncCallback\<void>): void
7912
7913Unregisters the callback function that is triggered when the buffer is released.
7914
7915**System capability**: SystemCapability.Multimedia.Image.ImageReceiver
7916
7917**Parameters**
7918
7919| Name  | Type                | Mandatory| Description                                    |
7920| -------- | -------------------- |----|----------------------------------------|
7921| type     | string               | Yes | Type of event, which is **'imageArrival'**.|
7922| callback | AsyncCallback\<void> | No | Callback to unregister.        |
7923
7924**Example**
7925
7926```ts
7927let callbackFunc = ()=>{
7928    // do something.
7929}
7930receiver.on('imageArrival', callbackFunc)
7931receiver.off('imageArrival', callbackFunc)
7932```
7933
7934### release<sup>9+</sup>
7935
7936release(callback: AsyncCallback\<void>): void
7937
7938Releases this ImageReceiver instance. This API uses an asynchronous callback to return the result.
7939
7940ArkTS supports memory reclamation. Even if the application does not call **release()**, the memory of the ImageReceiver object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
7941
7942**System capability**: SystemCapability.Multimedia.Image.ImageReceiver
7943
7944**Parameters**
7945
7946| Name  | Type                | Mandatory| Description                    |
7947| -------- | -------------------- | ---- | ------------------------ |
7948| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. |
7949
7950**Example**
7951
7952```ts
7953import { BusinessError } from '@kit.BasicServicesKit';
7954
7955receiver.release((err: BusinessError) => {
7956  if (err) {
7957    console.error(`Failed to release the receiver.code ${err.code},message is ${err.message}`);
7958  } else {
7959    console.info('Succeeded in releasing the receiver.');
7960  }
7961})
7962```
7963
7964### release<sup>9+</sup>
7965
7966release(): Promise\<void>
7967
7968Releases this ImageReceiver instance. This API uses a promise to return the result.
7969
7970ArkTS supports memory reclamation. Even if the application does not call **release()**, the memory of the ImageReceiver object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
7971
7972**System capability**: SystemCapability.Multimedia.Image.ImageReceiver
7973
7974**Return value**
7975
7976| Type          | Description              |
7977| -------------- | ------------------ |
7978| Promise\<void> |  Promise that returns no value.|
7979
7980**Example**
7981
7982```ts
7983import { BusinessError } from '@kit.BasicServicesKit';
7984
7985receiver.release().then(() => {
7986  console.info('Succeeded in releasing the receiver.');
7987}).catch((error: BusinessError) => {
7988  console.error(`Failed to release the receiver.code ${error.code},message is ${error.message}`);
7989})
7990```
7991
7992## image.createImageCreator<sup>11+</sup>
7993
7994createImageCreator(size: Size, format: ImageFormat, capacity: number): ImageCreator
7995
7996Creates an ImageCreator instance by specifying the image size, format, and capacity.
7997
7998**System capability**: SystemCapability.Multimedia.Image.ImageCreator
7999
8000**Parameters**
8001
8002| Name  | Type  | Mandatory| Description                  |
8003| -------- | ------ | ---- | ---------------------- |
8004| size    | [Size](#size)  | Yes  | Default size of the image.      |
8005| format   | [ImageFormat](#imageformat9) | Yes  | Image format, for example, YCBCR_422_SP or JPEG.            |
8006| capacity | number | Yes  | Maximum number of images that can be accessed at the same time.|
8007
8008**Return value**
8009
8010| Type                          | Description                                   |
8011| ------------------------------ | --------------------------------------- |
8012| [ImageCreator](#imagecreator9) | ImageCreator instance.|
8013
8014
8015**Error codes**
8016
8017For details about the error codes, see [Image Error Codes](errorcode-image.md).
8018
8019| ID| Error Message|
8020| ------- | --------------------------------------------|
8021| 401| Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types;          |
8022
8023**Example**
8024
8025```ts
8026let size: image.Size = {
8027  height: 8192,
8028  width: 8
8029}
8030let creator: image.ImageCreator = image.createImageCreator(size, image.ImageFormat.JPEG, 8);
8031```
8032
8033## image.createImageCreator<sup>(deprecated)</sup>
8034
8035createImageCreator(width: number, height: number, format: number, capacity: number): ImageCreator
8036
8037Creates an ImageCreator instance by specifying the image width, height, format, and capacity.
8038
8039> **NOTE**
8040>
8041> This API is deprecated since API version 11. You are advised to use [createImageCreator](#imagecreateimagecreator11).
8042
8043**System capability**: SystemCapability.Multimedia.Image.ImageCreator
8044
8045**Parameters**
8046
8047| Name  | Type  | Mandatory| Description                  |
8048| -------- | ------ | ---- | ---------------------- |
8049| width    | number | Yes  | Default image width, in px.      |
8050| height   | number | Yes  | Default image height, in px.      |
8051| format   | number | Yes  | Image format, for example, YCBCR_422_SP or JPEG.            |
8052| capacity | number | Yes  | Maximum number of images that can be accessed at the same time.|
8053
8054**Return value**
8055
8056| Type                          | Description                                   |
8057| ------------------------------ | --------------------------------------- |
8058| [ImageCreator](#imagecreator9) | ImageCreator instance.|
8059
8060**Example**
8061
8062```ts
8063let creator: image.ImageCreator = image.createImageCreator(8192, 8, image.ImageFormat.JPEG, 8);
8064```
8065
8066## ImageCreator<sup>9+</sup>
8067
8068Provides APIs for applications to request an image data area and compile image data.
8069Before calling any APIs in ImageCreator, you must create an [ImageCreator](#imagecreator9) instance. ImageCreator does not support multiple threads.
8070
8071### Properties
8072
8073**System capability**: SystemCapability.Multimedia.Image.ImageCreator
8074
8075| Name    | Type                        | Read Only| Optional| Description              |
8076| -------- | ---------------------------- | ---- | ---- | ------------------ |
8077| capacity | number                       | Yes  | No  | Maximum number of images that can be accessed at the same time.|
8078| format   | [ImageFormat](#imageformat9) | Yes  | No  | Image format.        |
8079
8080### dequeueImage<sup>9+</sup>
8081
8082dequeueImage(callback: AsyncCallback\<Image>): void
8083
8084Obtains an image buffer from the idle queue and writes image data into it. This API uses an asynchronous callback to return the result.
8085
8086**System capability**: SystemCapability.Multimedia.Image.ImageCreator
8087
8088**Parameters**
8089
8090| Name       | Type                                   | Mandatory| Description                |
8091| ------------- | ---------------------------------------| ---- | -------------------- |
8092| callback      | AsyncCallback\<[Image](#image9)>  | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the latest image obtained; otherwise, **err** is an error object. |
8093
8094**Example**
8095
8096```ts
8097import { BusinessError } from '@kit.BasicServicesKit';
8098
8099creator.dequeueImage((err: BusinessError, img: image.Image) => {
8100  if (err) {
8101    console.error(`Failed to dequeue the Image.code ${err.code},message is ${err.message}`);
8102  } else {
8103    console.info('Succeeded in dequeuing the Image.');
8104  }
8105});
8106```
8107
8108### dequeueImage<sup>9+</sup>
8109
8110dequeueImage(): Promise\<Image>
8111
8112Obtains an image buffer from the idle queue and writes image data into it. This API uses a promise to return the result.
8113
8114**System capability**: SystemCapability.Multimedia.Image.ImageCreator
8115
8116**Return value**
8117
8118| Type            | Description          |
8119| --------------- | ------------- |
8120| Promise\<[Image](#image9)> | Promise used to return the latest image.|
8121
8122**Example**
8123
8124```ts
8125import { BusinessError } from '@kit.BasicServicesKit';
8126
8127creator.dequeueImage().then((img: image.Image) => {
8128  console.info('Succeeded in dequeuing the Image.');
8129}).catch((error: BusinessError) => {
8130  console.error(`Failed to dequeue the Image.code ${error.code},message is ${error.message}`);
8131})
8132```
8133
8134### queueImage<sup>9+</sup>
8135
8136queueImage(interface: Image, callback: AsyncCallback\<void>): void
8137
8138Places the drawn image in the queue. This API uses an asynchronous callback to return the result.
8139
8140**System capability**: SystemCapability.Multimedia.Image.ImageCreator
8141
8142**Parameters**
8143
8144| Name       | Type                    | Mandatory| Description                |
8145| ------------- | -------------------------| ---- | -------------------- |
8146| interface     | [Image](#image9)                    | Yes  | Drawn image.|
8147| callback      | AsyncCallback\<void>     | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. |
8148
8149**Example**
8150
8151```ts
8152import { BusinessError } from '@kit.BasicServicesKit';
8153
8154creator.dequeueImage().then((img: image.Image) => {
8155  // Draw the image.
8156  img.getComponent(4).then((component : image.Component) => {
8157    let bufferArr: Uint8Array = new Uint8Array(component.byteBuffer);
8158    for (let i = 0; i < bufferArr.length; i += 4) {
8159      bufferArr[i] = 0; //B
8160      bufferArr[i + 1] = 0; //G
8161      bufferArr[i + 2] = 255; //R
8162      bufferArr[i + 3] = 255; //A
8163    }
8164  })
8165  creator.queueImage(img, (err: BusinessError) => {
8166    if (err) {
8167      console.error(`Failed to queue the Image.code ${err.code},message is ${err.message}`);
8168    } else {
8169      console.info('Succeeded in queuing the Image.');
8170    }
8171  })
8172})
8173
8174```
8175
8176### queueImage<sup>9+</sup>
8177
8178queueImage(interface: Image): Promise\<void>
8179
8180Places the drawn image in the queue. This API uses a promise to return the result.
8181
8182**System capability**: SystemCapability.Multimedia.Image.ImageCreator
8183
8184**Parameters**
8185
8186| Name         | Type    | Mandatory| Description               |
8187| ------------- | --------| ---- | ------------------- |
8188| interface     | [Image](#image9)   | Yes  | Drawn image.|
8189
8190**Return value**
8191
8192| Type           | Description          |
8193| -------------- | ------------- |
8194| Promise\<void> | Promise that returns no value.|
8195
8196**Example**
8197
8198```ts
8199import { BusinessError } from '@kit.BasicServicesKit';
8200
8201creator.dequeueImage().then((img: image.Image) => {
8202  // Draw the image.
8203  img.getComponent(4).then((component: image.Component) => {
8204    let bufferArr: Uint8Array = new Uint8Array(component.byteBuffer);
8205    for (let i = 0; i < bufferArr.length; i += 4) {
8206      bufferArr[i] = 0; //B
8207      bufferArr[i + 1] = 0; //G
8208      bufferArr[i + 2] = 255; //R
8209      bufferArr[i + 3] = 255; //A
8210    }
8211  })
8212  creator.queueImage(img).then(() => {
8213    console.info('Succeeded in queuing the Image.');
8214  }).catch((error: BusinessError) => {
8215    console.error(`Failed to queue the Image.code ${error.code},message is ${error.message}`);
8216  })
8217})
8218
8219```
8220
8221### on<sup>9+</sup>
8222
8223on(type: 'imageRelease', callback: AsyncCallback\<void>): void
8224
8225Listens for image release events. This API uses an asynchronous callback to return the result.
8226
8227**System capability**: SystemCapability.Multimedia.Image.ImageCreator
8228
8229**Parameters**
8230
8231| Name       | Type                    | Mandatory| Description                |
8232| ------------- | -------------------------| ---- | -------------------- |
8233| type          | string                   | Yes  | Type of event, which is **'imageRelease'**.|
8234| callback      | AsyncCallback\<void>     | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. |
8235
8236**Example**
8237
8238```ts
8239import { BusinessError } from '@kit.BasicServicesKit';
8240
8241creator.on('imageRelease', (err: BusinessError) => {
8242  if (err) {
8243    console.error(`Failed to get the imageRelease callback.code ${err.code},message is ${err.message}`);
8244  } else {
8245    console.info('Succeeded in getting imageRelease callback.');
8246  }
8247})
8248```
8249
8250### off<sup>13+</sup>
8251
8252off(type: 'imageRelease', callback?: AsyncCallback\<void>): void
8253
8254Unregisters the callback function that is triggered when the buffer is released.
8255
8256**System capability**: SystemCapability.Multimedia.Image.ImageCreator
8257
8258**Parameters**
8259
8260| Name       | Type                    | Mandatory| Description                                        |
8261| ------------- | -------------------------|----|--------------------------------------------|
8262| type          | string                   | Yes | Type of event, which is **'imageRelease'**.                   |
8263| callback      | AsyncCallback\<void>     | No | Callback to unregister.|
8264
8265**Example**
8266
8267```ts
8268let callbackFunc = ()=>{
8269    // do something.
8270}
8271creator.on('imageRelease', callbackFunc)
8272creator.off('imageRelease', callbackFunc)
8273```
8274
8275### release<sup>9+</sup>
8276
8277release(callback: AsyncCallback\<void>): void
8278
8279Releases this ImageCreator instance. This API uses an asynchronous callback to return the result.
8280
8281ArkTS supports memory reclamation. Even if the application does not call **release()**, the memory of the ImageCreator object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
8282
8283**System capability**: SystemCapability.Multimedia.Image.ImageCreator
8284
8285**Parameters**
8286
8287| Name          | Type                    | Mandatory| Description                |
8288| ------------- | -------------------------| ---- | -------------------- |
8289| callback      | AsyncCallback\<void>     | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
8290
8291**Example**
8292
8293```ts
8294import { BusinessError } from '@kit.BasicServicesKit';
8295
8296creator.release((err: BusinessError) => {
8297  if (err) {
8298    console.error(`Failed to release the creator.code ${err.code},message is ${err.message}`);
8299  } else {
8300    console.info('Succeeded in releasing creator.');
8301  }
8302});
8303```
8304### release<sup>9+</sup>
8305
8306release(): Promise\<void>
8307
8308Releases this ImageCreator instance. This API uses a promise to return the result.
8309
8310ArkTS supports memory reclamation. Even if the application does not call **release()**, the memory of the ImageCreator object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
8311
8312**System capability**: SystemCapability.Multimedia.Image.ImageCreator
8313
8314**Return value**
8315
8316| Type           | Description          |
8317| -------------- | ------------- |
8318| Promise\<void> | Promise that returns no value.|
8319
8320**Example**
8321
8322```ts
8323import { BusinessError } from '@kit.BasicServicesKit';
8324
8325creator.release().then(() => {
8326  console.info('Succeeded in releasing creator.');
8327}).catch((error: BusinessError) => {
8328  console.error(`Failed to release the creator.code ${error.code},message is ${error.message}`);
8329})
8330```
8331
8332## Image<sup>9+</sup>
8333
8334Provides APIs for basic image operations, including obtaining image information and reading and writing image data. An Image instance is returned when [readNextImage](#readnextimage9) and [readLatestImage](#readlatestimage9) are called.
8335
8336### Properties
8337
8338**System capability**: SystemCapability.Multimedia.Image.Core
8339
8340| Name    | Type              | Read Only| Optional| Description                                              |
8341| -------- | ------------------ | ---- | ---- | -------------------------------------------------- |
8342| clipRect | [Region](#region8) | Yes  | Yes  | Image area to be cropped.                                |
8343| 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).                               |
8344| format   | number             | Yes  | No  | Image format. For details, see [OH_NativeBuffer_Format](../apis-arkgraphics2d/capi-native-buffer-h.md#oh_nativebuffer_format).|
8345| 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](#getimageproperty11) to read the related EXIF information.|
8346
8347### getComponent<sup>9+</sup>
8348
8349getComponent(componentType: ComponentType, callback: AsyncCallback\<Component>): void
8350
8351Obtains the component buffer from the Image instance based on the color component type. This API uses an asynchronous callback to return the result.
8352
8353**System capability**: SystemCapability.Multimedia.Image.Core
8354
8355**Parameters**
8356
8357| Name       | Type                                   | Mandatory| Description                |
8358| ------------- | --------------------------------------- | ---- | -------------------- |
8359| componentType | [ComponentType](#componenttype9)        | Yes  | Color component type of the image. (Currently, only **ComponentType:JPEG** is supported. The format actually returned is determined by the producer, for example, camera.)   |
8360| callback      | AsyncCallback<[Component](#component9)> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the component buffer obtained; otherwise, **err** is an error object. |
8361
8362**Example**
8363
8364```ts
8365import { BusinessError } from '@kit.BasicServicesKit';
8366
8367img.getComponent(4, (err: BusinessError, component: image.Component) => {
8368  if (err) {
8369    console.error(`Failed to get the component.code ${err.code},message is ${err.message}`);
8370  } else {
8371    console.info('Succeeded in getting component.');
8372  }
8373})
8374```
8375
8376### getComponent<sup>9+</sup>
8377
8378getComponent(componentType: ComponentType): Promise\<Component>
8379
8380Obtains the component buffer from the Image instance based on the color component type. This API uses a promise to return the result.
8381
8382**System capability**: SystemCapability.Multimedia.Image.Core
8383
8384**Parameters**
8385
8386| Name       | Type                            | Mandatory| Description            |
8387| ------------- | -------------------------------- | ---- | ---------------- |
8388| componentType | [ComponentType](#componenttype9) | Yes  | Color component type of the image. (Currently, only **ComponentType:JPEG** is supported. The format actually returned is determined by the producer, for example, camera.)|
8389
8390**Return value**
8391
8392| Type                             | Description                             |
8393| --------------------------------- | --------------------------------- |
8394| Promise<[Component](#component9)> | Promise used to return the component buffer.|
8395
8396**Example**
8397
8398```ts
8399import { BusinessError } from '@kit.BasicServicesKit';
8400
8401img.getComponent(4).then((component: image.Component) => {
8402  console.info('Succeeded in getting component.');
8403}).catch((error: BusinessError) => {
8404  console.error(`Failed to get the component.code ${error.code},message is ${error.message}`);
8405})
8406```
8407
8408### release<sup>9+</sup>
8409
8410release(callback: AsyncCallback\<void>): void
8411
8412Releases this Image instance. This API uses an asynchronous callback to return the result.
8413
8414The corresponding resources must be released before another image arrives.
8415
8416ArkTS supports memory reclamation. Even if the application does not call **release()**, the memory of the Image object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
8417
8418**System capability**: SystemCapability.Multimedia.Image.Core
8419
8420**Parameters**
8421
8422| Name  | Type                | Mandatory| Description          |
8423| -------- | -------------------- | ---- | -------------- |
8424| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. |
8425
8426**Example**
8427
8428```ts
8429import { BusinessError } from '@kit.BasicServicesKit';
8430
8431img.release((err: BusinessError) => {
8432  if (err) {
8433    console.error(`Failed to release the image instance.code ${err.code},message is ${err.message}`);
8434  } else {
8435    console.info('Succeeded in releasing the image instance.');
8436  }
8437})
8438```
8439
8440### release<sup>9+</sup>
8441
8442release(): Promise\<void>
8443
8444Releases this Image instance. This API uses a promise to return the result.
8445
8446The corresponding resources must be released before another image arrives.
8447
8448ArkTS supports memory reclamation. Even if the application does not call **release()**, the memory of the Image object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
8449
8450**System capability**: SystemCapability.Multimedia.Image.Core
8451
8452**Return value**
8453
8454| Type          | Description                 |
8455| -------------- | --------------------- |
8456| Promise\<void> |  Promise that returns no value.|
8457
8458**Example**
8459
8460```ts
8461import { BusinessError } from '@kit.BasicServicesKit';
8462
8463img.release().then(() => {
8464  console.info('Succeeded in releasing the image instance.');
8465}).catch((error: BusinessError) => {
8466  console.error(`Failed to release the image instance.code ${error.code},message is ${error.message}`);
8467})
8468```
8469
8470## PositionArea<sup>7+</sup>
8471
8472Describes area information in an image.
8473
8474**Widget capability**: This API can be used in ArkTS widgets since API version 12.
8475
8476**Atomic service API**: This API can be used in atomic services since API version 11.
8477
8478**System capability**: SystemCapability.Multimedia.Image.Core
8479
8480| Name  | Type              | Read Only|  Optional| Description                                                        |
8481| ------ | ------------------ | ---| -----|------------------------------------------------------- |
8482| pixels | ArrayBuffer        | No|   No | Pixels of the image. Only pixel data in BGRA_8888 format is supported.|
8483| offset | number             | No|   No |  Offset for data reading, in bytes.                                                    |
8484| stride | number             | No|   No | Number of bytes from one row of pixels in memory to the next row of pixels in memory. The value of **stride** must be greater than or equal to the value of **region.size.width** multiplied by 4.                  |
8485| region | [Region](#region8) | No|   No |Region to read or write. The width of the region to write plus the X coordinate cannot be greater than the width of the original image. The height of the region to write plus the Y coordinate cannot be greater than the height of the original image.|
8486
8487## ImageInfo
8488
8489Describes image information.
8490
8491**System capability**: SystemCapability.Multimedia.Image.Core
8492
8493| Name| Type         | Read Only| Optional| Description      |
8494| ---- | ------------- | --- |-----|---------- |
8495| size<sup>6+</sup> | [Size](#size) | No|  No |Image size.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.|
8496| density<sup>9+</sup> | number | No | No|Pixel density, in ppi.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.|
8497| stride<sup>11+</sup> | number | No | No | Number of bytes from one row of pixels in memory to the next row of pixels in memory.stride >= region.size.width*4 <br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.|
8498| pixelFormat<sup>12+</sup> | [PixelMapFormat](#pixelmapformat7) | No |  No| Pixel format.<br>**Atomic service API**: This API can be used in atomic services since API version 12.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.|
8499| alphaType<sup>12+</sup> | [AlphaType](#alphatype9)  | No |  No |Alpha type.<br>**Atomic service API**: This API can be used in atomic services since API version 12.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.|
8500| mimeType<sup>12+</sup> | string  |  No |   No |Actual image format (MIME type). |
8501| isHdr<sup>12+</sup> | boolean  |  No | No | Whether the image is an HDR image. The value **true** means an HDR image, and **false** means an SDR image. For [ImageSource](#imagesource), this parameter specifies whether the source image is in HDR format. For [PixelMap](#pixelmap7), this parameter specifies whether the decoded PixelMap is in HDR format.|
8502
8503## Size
8504
8505Describes the size of an image.
8506
8507**Widget capability**: This API can be used in ArkTS widgets since API version 12.
8508
8509**Atomic service API**: This API can be used in atomic services since API version 11.
8510
8511**System capability**: SystemCapability.Multimedia.Image.Core
8512
8513| Name  | Type  | Read Only|  Optional |Description          |
8514| ------ | ------ | -- |-----| -------------- |
8515| height | number | No |  No |Image height, in px.|
8516| width  | number | No |  No| Image width, in px.|
8517
8518## PixelMapFormat<sup>7+</sup>
8519
8520Enumerates the pixel formats of images.
8521
8522**System capability**: SystemCapability.Multimedia.Image.Core
8523
8524| Name                  |   Value  | Description             |
8525| ---------------------- | ------ | ----------------- |
8526| UNKNOWN                | 0      | Unknown format.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.       |
8527| ARGB_8888<sup>18+</sup> | 1 | The color information consists of four components: alpha, R (Red), G (Green), and B (Blue). Each component occupies 8 bits, and the total length is 32 bits. Currently, this format supports only PixelMap APIs.|
8528| RGB_565                | 2      | The color information consists of three components: R (Red), G (Green), and B (Blue), which occupies five bits, six bits, and five bits, respectively. The total length is 16 bits.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.    |
8529| RGBA_8888              | 3      | The color information consists of four components: R (Red), G (Green), B (Blue), and alpha. Each component occupies 8 bits, and the total length is 32 bits.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.|
8530| BGRA_8888<sup>9+</sup> | 4      | The color information consists of four components: B (Blue), G (Green), R (Red), and alpha. Each component occupies 8 bits, and the total length is 32 bits.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.|
8531| RGB_888<sup>9+</sup>   | 5      | The color information consists of three components: R (Red), G (Green), and B (Blue). Each component occupies 8 bits, and the total length is 24 bits.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.  |
8532| ALPHA_8<sup>9+</sup>   | 6      | The color information consists of only the alpha component, which occupies eight bits.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.  |
8533| RGBA_F16<sup>9+</sup>  | 7      | The color information consists of four components: R (Red), G (Green), B (Blue), and alpha. Each component occupies 16 bits, and the total length is 64 bits.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12. |
8534| NV21<sup>9+</sup>      | 8      | YVU pixel arrangement, where the V component precedes the U component. The color information consists of the luminance component Y and the interleaved chrominance components V and U. The Y component occupies 8 bits, and the UV components occupy 4 bits on average due to 4:2:0 sampling. The total length is 12 bits on average.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.     |
8535| NV12<sup>9+</sup>      | 9      | YUV pixel arrangement, where the U component precedes the V component. The color information consists of the luminance component Y and the interleaved chrominance components U and V. The Y component occupies 8 bits, and the UV components occupy 4 bits on average due to 4:2:0 sampling. The total length is 12 bits on average.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.     |
8536| RGBA_1010102<sup>12+</sup> | 10 | The color information consists of four components: R (Red), G (Green), B (Blue), and alpha. R, G, and B each occupy 10 bits, and alpha occupies 2 bits. The total length is 32 bits.|
8537| YCBCR_P010<sup>12+</sup> | 11 | The color information consists of the luminance component Y and the chrominance components Cb and Cr. Each component has effective 10 bits. In storage, the Y plane uses 16 bits per pixel (10 of which are effective). The UV plane is interleaved, with every four pixels taking up 32 bits of data (each chrominance component having 10 effective bits), resulting in an average of 15 effective bits overall.
8538| YCRCB_P010<sup>12+</sup> | 12 | The color information consists of the luminance component Y and the chrominance components Cr and Cb. Each component has effective 10 bits. In storage, the Y plane uses 16 bits per pixel (10 of which are effective). The UV plane is interleaved, with every four pixels taking up 32 bits of data (each chrominance component having 10 effective bits), resulting in an average of 15 effective bits overall. |
8539| ASTC_4x4<sup>18+</sup> | 102 | The storage format is ASTC_4x4, and the memory usage is only 1/4 of that of RGBA_8888. This format is used only for direct display and does not support pixel access or post-processing editing. |
8540
8541## AlphaType<sup>9+</sup>
8542
8543Enumerates the alpha types of images.
8544
8545**Widget capability**: This API can be used in ArkTS widgets since API version 12.
8546
8547**Atomic service API**: This API can be used in atomic services since API version 11.
8548
8549**System capability**: SystemCapability.Multimedia.Image.Core
8550
8551| Name    |   Value  | Description                   |
8552| -------- | ------ | ----------------------- |
8553| UNKNOWN  | 0      | Unknown alpha type.           |
8554| OPAQUE   | 1      | There is no alpha or the image is opaque.|
8555| PREMUL   | 2      | Premultiplied alpha.        |
8556| UNPREMUL | 3      | RGB non-premultiplied alpha.      |
8557
8558## AuxiliaryPictureType<sup>13+</sup>
8559
8560Enumerates the auxiliary pictures types.
8561
8562**System capability**: SystemCapability.Multimedia.Image.Core
8563
8564| Name         | Value  | Description        |
8565| ------------- | ---- | ------------ |
8566| GAINMAP       | 1    | Gain map, a mechanism for transforming an SDR image into an HDR image capable of display adjustment. It is a set of combinations describing how to apply gain map metadata.    |
8567| DEPTH_MAP     | 2    | Depth map, which stores the depth data of an image. It captures the distance between each pixel and the camera to provide 3D scene structure. It is usually used for 3D modeling and scene comprehension.    |
8568| UNREFOCUS_MAP | 3    | Defocused portrait original image, which provides a method to emphasize background blur in portrait photographing. It helps users select a focus region in post-processing, allowing for greater creative control.  |
8569| LINEAR_MAP    | 4    | Linear map, which is used to provide additional viewpoints or supplementary information. It is usually used to enhance visual effects and can contain linear representations of lighting, colors, or other visual elements in a scene.    |
8570| FRAGMENT_MAP  | 5    | Fragment map, which indicates regions obscured by watermarks in the original image. It is used to remove or correct the watermark interference, thereby enhancing the image completeness and visibility.|
8571
8572## AuxiliaryPictureInfo<sup>13+</sup>
8573
8574Describes the auxiliary picture information.
8575
8576**System capability**: SystemCapability.Multimedia.Image.Core
8577
8578| Name                     | Type                                                        | Read Only| Optional| Description                                                        |
8579| ------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
8580| auxiliaryPictureType      | [AuxiliaryPictureType](#auxiliarypicturetype13)              | No  | No  | Auxiliary picture type.                                          |
8581| size         | [Size](#size)                                                | No  | No  | Image size.|
8582| rowStride                 | number                                                       | No  | No  | Row stride.                                                      |
8583| pixelFormat | [PixelMapFormat](#pixelmapformat7)                           | No  | No  | Pixel format.|
8584| colorSpace                | [colorSpaceManager.ColorSpaceManager](../apis-arkgraphics2d/js-apis-colorSpaceManager.md#colorspacemanager) | No  | No  | Color space.                                              |
8585
8586## MetadataType<sup>13+</sup>
8587
8588Enumerates image metadata types.
8589
8590**System capability**: SystemCapability.Multimedia.Image.Core
8591
8592| Name             | Value  | Description              |
8593| ----------------- | ---- | ------------------ |
8594| EXIF_METADATA     | 1    | EXIF data.        |
8595| FRAGMENT_METADATA | 2    | Fragment map metadata.|
8596
8597## ScaleMode<sup>9+</sup>
8598
8599Enumerates the scale modes of images.
8600
8601**Widget capability**: This API can be used in ArkTS widgets since API version 12.
8602
8603**Atomic service API**: This API can be used in atomic services since API version 11.
8604
8605**System capability**: SystemCapability.Multimedia.Image.Core
8606
8607| Name           |   Value  | Description                                              |
8608| --------------- | ------ | -------------------------------------------------- |
8609| CENTER_CROP     | 1      | Scales the image so that it fills the requested bounds of the target and crops the extra.|
8610| FIT_TARGET_SIZE | 0      | Reduces the image size to the dimensions of the target.                          |
8611
8612## SourceOptions<sup>9+</sup>
8613
8614Defines image source initialization options.
8615
8616**Widget capability**: This API can be used in ArkTS widgets since API version 12.
8617
8618**Atomic service API**: This API can be used in atomic services since API version 11.
8619
8620**System capability**: SystemCapability.Multimedia.Image.Core
8621
8622| Name             | Type                              | Read Only| Optional| Description              |
8623| ----------------- | ---------------------------------- | ---- | ---- | ------------------ |
8624| sourceDensity     | number                             | No  | No  | Pixel density of the image resource, in ppi.<br>If **desiredSize** is not set in [DecodingOptions](#decodingoptions7) and **SourceOptions.sourceDensity** and **DecodingOptions.fitDensity** are not 0, the PixelMap output after decoding will be scaled.<br>The formula for calculating the width after scaling is as follows (the same applies to the height): (width * fitDensity + (sourceDensity >> 1)) / sourceDensity.|
8625| sourcePixelFormat | [PixelMapFormat](#pixelmapformat7) | No  | Yes  | Image pixel format. The default value is **UNKNOWN**.    |
8626| sourceSize        | [Size](#size)                      | No  | Yes  | Image pixel size. The default value is null.    |
8627
8628
8629## InitializationOptions<sup>8+</sup>
8630
8631Defines PixelMap initialization options.
8632
8633**System capability**: SystemCapability.Multimedia.Image.Core
8634
8635| Name                    | Type                              | Read Only|Optional|  Description          |
8636| ------------------------ | ---------------------------------- | ----| -----|  -------------- |
8637| alphaType<sup>9+</sup>   | [AlphaType](#alphatype9)           | No  | Yes| Alpha type. The default value is **IMAGE_ALPHA_TYPE_PREMUL**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.     |
8638| editable                 | boolean                            | No  | Yes| Whether the image is editable. The value **true** means that the image is editable, and **false** means the opposite. The default value is **false**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.|
8639| srcPixelFormat<sup>12+</sup>  | [PixelMapFormat](#pixelmapformat7) | No| Yes| Pixel format of the passed-in buffer data. The default value is **BGRA_8888**.|
8640| pixelFormat              | [PixelMapFormat](#pixelmapformat7) | No| Yes| Pixel format of the generated PixelMap. The default value is **RGBA_8888**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.    |
8641| scaleMode<sup>9+</sup>   | [ScaleMode](#scalemode9)           | No | Yes| Scale mode. The default value is **0**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.      |
8642| size                     | [Size](#size)                      | No | No|Image size.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.|
8643
8644## DecodingOptions<sup>7+</sup>
8645
8646Describes the image decoding options.
8647
8648**System capability**: SystemCapability.Multimedia.Image.ImageSource
8649
8650| Name              | Type                              | Read Only| Optional| Description            |
8651| ------------------ | ---------------------------------- | ---- | ---- | ---------------- |
8652| sampleSize         | number                             | No  | Yes  | Sampling size of the thumbnail. The default value is **1**. Currently, the value can only be **1**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.|
8653| rotate             | number                             | No  | Yes  | Rotation angle. The default value is **0**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.      |
8654| editable           | boolean                            | No  | Yes  | Whether the image is editable. The value **true** means that the image is editable, and **false** means the opposite. The default value is **false**. If this option is set to **false**, the image cannot be edited again, and operations such as writing pixels will fail.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12. |
8655| desiredSize        | [Size](#size)                      | No  | Yes  | Expected output size. The value must be a positive integer and defaults to the original image size. If the output size is different from the original size, the output is stretched or scaled to the specified size.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.  |
8656| desiredRegion      | [Region](#region8)                 | No  | Yes  | Rectangle specified by **Region** in the decoded image. When the original image is large and only a specific part of the image is required, you can set this parameter to improve performance. The default value is the original image size.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.      |
8657| desiredPixelFormat | [PixelMapFormat](#pixelmapformat7) | No  | Yes  | Pixel format for decoding. The default value is **RGBA_8888**. Only RGBA_8888, BGRA_8888, and RGB_565 are supported. RGB_565 is not supported for images with alpha channels, such as PNG, GIF, ICO, and WEBP.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.|
8658| index              | number                             | No  | Yes  | Index of the image to decode. The default value is **0**, indicating the first image. If this parameter is set to N, the (N-1)th image is used. For single-frame images, the value is always **0**. For multi-frame images such as animations, the value ranges from 0 to (Number of frames – 1).<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.  |
8659| fitDensity<sup>9+</sup> | number                        | No  | Yes  | Pixel density, in ppi. The default value is **0**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.  |
8660| desiredColorSpace<sup>11+</sup> | [colorSpaceManager.ColorSpaceManager](../apis-arkgraphics2d/js-apis-colorSpaceManager.md#colorspacemanager) | No  | Yes  | Target color space. The default value is **UNKNOWN**.|
8661| desiredDynamicRange<sup>12+</sup> | [DecodingDynamicRange](#decodingdynamicrange12) | No  | Yes  | Desired dynamic range. The default value is **SDR**.<br>This property cannot be set for an image source created using [CreateIncrementalSource](#imagecreateincrementalsource9). By default, the image source is decoded as SDR content.<br>If the platform does not support HDR, the setting is invalid and the content is decoded as SDR content by default.|
8662| cropAndScaleStrategy<sup>18+</sup> | [CropAndScaleStrategy](#cropandscalestrategy18) | No  | Yes  | If **desiredRegion** and **desiredSize** are both specified, the order of cropping and scaling is determined.<br>Only **SCALE_FIRST** and **CROP_FIRST** are supported.|
8663
8664## DecodingOptionsForPicture<sup>13+</sup>
8665
8666Describes the image decoding options.
8667
8668**System capability**: SystemCapability.Multimedia.Image.ImageSource
8669
8670| Name                    | Type                                                   | Read Only| Optional| Description                                                        |
8671| ------------------------ | ------------------------------------------------------- | ---- | ---- | ------------------------------------------------------------ |
8672| desiredAuxiliaryPictures | Array\<[AuxiliaryPictureType](#auxiliarypicturetype13)> | No  | No  | Auxiliary picture type. By default, all auxiliary picture types are decoded.|
8673
8674## Region<sup>8+</sup>
8675
8676Describes the region information.
8677
8678**Widget capability**: This API can be used in ArkTS widgets since API version 12.
8679
8680**Atomic service API**: This API can be used in atomic services since API version 11.
8681
8682**System capability**: SystemCapability.Multimedia.Image.Core
8683
8684| Name| Type         | Read Only| Optional| Description        |
8685| ---- | ------------- | ---- | ---- | ------------ |
8686| size<sup>7+</sup> | [Size](#size) | No  | No  | Region size.  |
8687| x<sup>7+</sup>    | number        | No  | No | X coordinate of the upper left corner of the region, in px.|
8688| y<sup>7+</sup>    | number        | No | No | Y coordinate of the upper left corner of the region, in px.|
8689
8690## PackingOption
8691
8692Describes the options for image encoding.
8693
8694**System capability**: SystemCapability.Multimedia.Image.ImagePacker
8695
8696| Name   | Type  | Read Only| Optional| Description                                               |
8697| ------- | ------ | ---- | ---- | --------------------------------------------------- |
8698| format  | string | No  | No  | Format of the packed image.<br>Currently, only the following formats are supported: image/jpeg, image/webp, image/png, image/heic (or image/heif)<sup>12+</sup>, image/sdr_astc_4x4<sup>18+</sup>, and image/sdr_sut_superfast_4x4<sup>18+</sup> (depending on the hardware).<br>**NOTE**: The JPEG format does not support the alpha channel. If the JPEG format with the alpha channel is used for data encoding, the transparent color turns black.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
8699| quality | number | No  | No  | Quality of the output image set. This parameter takes effect only for JPEG and HEIF images. The value ranges from 0 to 100. The value **0** means the lowest quality, and **100** means the highest quality. The higher the quality, the larger the space occupied by the generated image. WebP and PNG images are lossless.<br>In the case of sdr_astc_4x4 encoding, the parameter can be set to **92** and **85**.<br>In the case of sut encoding, the parameter can be set to **92**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
8700| bufferSize<sup>9+</sup> | number | No  | Yes  | Size of the buffer for receiving the encoded data, in bytes. If this parameter is not set, the default value 25 MB is used. If the size of an image exceeds 25 MB, you must specify the size. The value of **bufferSize** must be greater than the size of the encoded image. The use of [packToFile](#packtofile11) is not restricted by this parameter.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
8701| desiredDynamicRange<sup>12+</sup> | [PackingDynamicRange](#packingdynamicrange12) | No  | Yes  | Desired dynamic range. The default value is **SDR**.|
8702| needsPackProperties<sup>12+</sup> | boolean | No  | Yes  | Whether to encode image property information, for example, EXIF. The value **true** means to encode image property information, and **false** means the opposite. The default value is **false**.|
8703
8704## PackingOptionsForSequence<sup>18+</sup>
8705
8706Defines the options for encoding animated images.
8707
8708**System capability**: SystemCapability.Multimedia.Image.ImagePacker
8709
8710| Name         | Type          | Read Only| Optional| Description                                                        |
8711| ------------- | -------------- | ---- | ---- | ------------------------------------------------------------ |
8712| frameCount    | number         | No  | No  | Number of frames specified in GIF encoding.                                       |
8713| delayTimeList | Array\<number> | No  | No  | Delay time of each frame in GIF encoding. The value must be greater than 0.<br>The unit is 10 milliseconds. For example, if this parameter is set to 10, the actual delay per frame is 100 ms.<br>If the array length is less than **frameCount**, the last value in the array will be used for the remaining frames.|
8714| disposalTypes | Array\<number> | No  | Yes  | Array that defines how each image frame transitions. If the array length is less than **frameCount**, the last value in the array will be used for the remaining frames. The values can be:<br>- **0**: No operation is required.<br>- **1**: Keeps the image unchanged.<br>- **2**: Restores the background color.<br>- **3**: Restores to the previous state.|
8715| loopCount     | number         | No  | Yes  | Number of times that the output image in GIF encoding loops. The value range is [0, 65535].<br>The value **0** means an infinite loop. If this field is not carried, loop playback is not performed.|
8716
8717## ImagePropertyOptions<sup>11+</sup>
8718
8719Describes the image properties.
8720
8721**System capability**: SystemCapability.Multimedia.Image.ImageSource
8722
8723| Name        | Type  | Read Only| Optional| Description        |
8724| ------------ | ------ | ---- | ---- | ------------ |
8725| index        | number | No  | Yes  | Index of the image. The default value is **0**.  |
8726| defaultValue | string | No  | Yes  | Default property value. The default value is null.|
8727
8728## GetImagePropertyOptions<sup>(deprecated)</sup>
8729
8730Describes the image properties.
8731
8732> **NOTE**
8733>
8734> This API is deprecated since API version 11. You are advised to use [ImagePropertyOptions](#imagepropertyoptions11).
8735
8736**System capability**: SystemCapability.Multimedia.Image.ImageSource
8737
8738| Name        | Type  | Read Only| Optional| Description        |
8739| ------------ | ------ | ---- | ---- | ------------ |
8740| index        | number | No  | Yes  | Index of the image. The default value is **0**.  |
8741| defaultValue | string | No  | Yes  | Default property value. The default value is null.|
8742
8743## PropertyKey<sup>7+</sup>
8744
8745Describes the exchangeable image file format (EXIF) data of an image.
8746
8747**System capability**: SystemCapability.Multimedia.Image.Core
8748
8749| Name              |   Value                   |   Description                   |
8750| ----------------- | ----------------------- |---------------------------|
8751| NEW_SUBFILE_TYPE <sup>12+</sup>           | "NewSubfileType"            | **Read/Write capability**: readable and writable<br> Data type of a subfile, such as a full-resolution image, a thumbnail, or a part of a multi-frame image. The value is a bit mask. The value 0 indicates a full-resolution image, **1** indicates a thumbnail, and **2** indicates a part of a multi-frame image.|
8752| SUBFILE_TYPE <sup>12+</sup>               | "SubfileType"               | **Read/Write capability**: readable and writable<br> Type of data contained in this subfile. This tag has been deprecated. Use **NewSubfileType** instead.|
8753| IMAGE_WIDTH                               | "ImageWidth"                | **Read/Write capability**: readable and writable<br> Image width.|
8754| IMAGE_LENGTH                              | "ImageLength"               | **Read/Write capability**: readable and writable<br> Image length.|
8755| BITS_PER_SAMPLE                           | "BitsPerSample"             | **Read/Write capability**: readable and writable<br> Number of bits per sample. For example, for RGB, which has three components, the format is 8, 8, 8.|
8756| COMPRESSION <sup>12+</sup>                | "Compression"               | **Read/Write capability**: readable and writable<br> Compression scheme used on the image data.|
8757| PHOTOMETRIC_INTERPRETATION <sup>12+</sup> | "PhotometricInterpretation" | **Read/Write capability**: readable and writable<br> Color space of the image data, for example, RGB or YCbCr.|
8758| IMAGE_DESCRIPTION<sup>10+</sup>           | "ImageDescription"          | **Read/Write capability**: readable and writable<br> Image description.|
8759| MAKE<sup>10+</sup>                        | "Make"                      | **Read/Write capability**: readable and writable<br> Manufacturer.|
8760| MODEL<sup>10+</sup>                       | "Model"                     | **Read/Write capability**: readable and writable<br> Device model.|
8761| STRIP_OFFSETS <sup>12+</sup>              | "StripOffsets"              | **Read/Write capability**: readable and writable<br> Byte offset of each strip.|
8762| ORIENTATION                               | "Orientation"               | **Read/Write capability**: readable and writable<br> Image orientation.<br>- 1: **Top-left**: The image is not rotated.<br>- 2: **Top-right**: The image is flipped horizontally.<br>- 3: **Bottom-right**: The image is rotated by 180°.<br>- 4: **Bottom-left**: The image is flipped vertically.<br>- 5: **Left-top**: The image is flipped horizontally and then rotated clockwise by 270°.<br>- 6: **Right-top**: The image is rotated clockwise by 90°.<br>- 7: **Right-bottom**: The image is vertically flipped and then rotated clockwise by 90°.<br>- 8: **Left-bottom**: The image is rotated clockwise by 270°.<br>- If an undefined value is read, **Unknown Value 0** is returned. The value of the property obtained is returned as a string. When modifying the property, you can specify the property either in the form of a number or a string.|
8763| SAMPLES_PER_PIXEL <sup>12+</sup>          | "SamplesPerPixel"           | **Read/Write capability**: readable and writable<br> Number of components per pixel. The value is 3 for RGB and YCbCr images. The **JPEG** key is used in JPEG compressed data.|
8764| ROWS_PER_STRIP <sup>12+</sup>             | "RowsPerStrip"              | **Read/Write capability**: readable and writable<br> Number of rows per strip.|
8765| STRIP_BYTE_COUNTS <sup>12+</sup>          | "StripByteCounts"           | **Read/Write capability**: readable and writable<br> Number of bytes in each strip after compression.|
8766| X_RESOLUTION <sup>12+</sup>               | "XResolution"               | **Read/Write capability**: readable and writable<br> Number of pixels per ResolutionUnit in the image width (X) direction.|
8767| Y_RESOLUTION <sup>12+</sup>               | "YResolution"               | **Read/Write capability**: readable and writable<br> Number of pixels per ResolutionUnit in the image height (Y) direction.|
8768| PLANAR_CONFIGURATION <sup>12+</sup>       | "PlanarConfiguration"       | **Read/Write capability**: readable and writable<br> Storage format of components of each pixel, which can be chunky or planar.|
8769| RESOLUTION_UNIT <sup>12+</sup>            | "ResolutionUnit"            | **Read/Write capability**: readable and writable<br> Unit of measurement for XResolution and YResolution.|
8770| TRANSFER_FUNCTION <sup>12+</sup>          | "TransferFunction"          | **Read/Write capability**: readable and writable<br> Transfer function for the image, which is usually used for color correction.|
8771| SOFTWARE <sup>12+</sup>                   | "Software"                  | **Read/Write capability**: readable and writable<br> Name and version number of the software used to create the image.|
8772| DATE_TIME<sup>10+</sup>                   | "DateTime"                  | **Read/Write capability**: readable and writable<br> Date and time of image creation. An example in the correct format is 2024:01:25 05:51:34.|
8773| ARTIST <sup>12+</sup>                     | "Artist"                    | **Read/Write capability**: readable and writable<br> Person who created the image.|
8774| WHITE_POINT <sup>12+</sup>                | "WhitePoint"                | **Read/Write capability**: readable and writable<br> Chromaticity of the white point of the image.|
8775| PRIMARY_CHROMATICITIES <sup>12+</sup>     | "PrimaryChromaticities"     | **Read/Write capability**: readable and writable<br> Chromaticities of the primaries of the image.|
8776| PHOTO_MODE<sup>10+</sup>                  | "PhotoMode"                 | **Read/Write capability**: readable and writable<br> Photographing mode.|
8777| JPEG_INTERCHANGE_FORMAT <sup>12+</sup>    | "JPEGInterchangeFormat"     | **Read/Write capability**: read-only<br> Offset of the SOI marker of a JPEG interchange format bitstream.|
8778| JPEG_INTERCHANGE_FORMAT_LENGTH <sup>12+</sup> | "JPEGInterchangeFormatLength" | **Read/Write capability**: read-only<br> Number of bytes of the JPEG stream.|
8779| YCBCR_COEFFICIENTS <sup>12+</sup>         | "YCbCrCoefficients"         | **Read/Write capability**: readable and writable<br> Transformation from RGB to YCbCr image data.|
8780| YCBCR_SUB_SAMPLING <sup>12+</sup>         | "YCbCrSubSampling"          | **Read/Write capability**: readable and writable<br> Subsampling factors used for the chrominance components of a YCbCr image.|
8781| YCBCR_POSITIONING <sup>12+</sup>          | "YCbCrPositioning"          | **Read/Write capability**: readable and writable<br> Positioning of subsampled chrominance components relative to luminance samples.|
8782| REFERENCE_BLACK_WHITE <sup>12+</sup>      | "ReferenceBlackWhite"       | **Read/Write capability**: readable and writable<br> A pair of headroom and footroom image data values (codes) for each pixel component.|
8783| COPYRIGHT <sup>12+</sup>                  | "Copyright"                 | **Read/Write capability**: readable and writable<br> Copyright notice of the image.|
8784| EXPOSURE_TIME<sup>9+</sup>                | "ExposureTime"              | **Read/Write capability**: readable and writable<br> Exposure time, for example, 1/33 seconds.|
8785| F_NUMBER<sup>9+</sup>                     | "FNumber"                   | **Read/Write capability**: readable and writable<br> F number, for example, f/1.8.|
8786| EXPOSURE_PROGRAM <sup>12+</sup>           | "ExposureProgram"           | **Read/Write capability**: readable and writable<br> Class of the program used by the camera to set exposure when the image was captured.|
8787| SPECTRAL_SENSITIVITY <sup>12+</sup>       | "SpectralSensitivity"       | **Read/Write capability**: readable and writable<br> Spectral sensitivity of each channel of the camera.|
8788| GPS_VERSION_ID <sup>12+</sup>             | "GPSVersionID"              | **Read/Write capability**: readable and writable<br> Version of GPSInfoIFD.|
8789| GPS_LATITUDE_REF                          | "GPSLatitudeRef"            | **Read/Write capability**: readable and writable<br> Whether the latitude is north or south latitude.|
8790| GPS_LATITUDE                              | "GPSLatitude"               | **Read/Write capability**: readable and writable<br> Image latitude. The value must be in the format of degree,minute,second, for example, 39,54,7.542.|
8791| GPS_LONGITUDE_REF                         | "GPSLongitudeRef"           | **Read/Write capability**: readable and writable<br> Whether the longitude is east or west longitude.|
8792| GPS_LONGITUDE                             | "GPSLongitude"              | **Read/Write capability**: readable and writable<br> Image longitude. The value must be in the format of degree,minute,second, for example, 116,19,42.16.|
8793| GPS_ALTITUDE_REF <sup>12+</sup>           | "GPSAltitudeRef"            | **Read/Write capability**: readable and writable<br> Whether the latitude is north or south latitude.|
8794| GPS_ALTITUDE <sup>12+</sup>               | "GPSAltitude"               | **Read/Write capability**: readable and writable<br> Altitude based on the reference in GPSAltitudeRef.|
8795| GPS_TIME_STAMP<sup>10+</sup>              | "GPSTimeStamp"              | **Read/Write capability**: readable and writable<br> GPS timestamp.|
8796| GPS_SATELLITES <sup>12+</sup>             | "GPSSatellites"             | **Read/Write capability**: readable and writable<br> GPS satellites used for measurement.|
8797| GPS_STATUS <sup>12+</sup>                 | "GPSStatus"                 | **Read/Write capability**: readable and writable<br> Status of the GPS receiver when the image was recorded.|
8798| GPS_MEASURE_MODE <sup>12+</sup>           | "GPSMeasureMode"            | **Read/Write capability**: readable and writable<br> GPS measurement pmode.|
8799| GPS_DOP <sup>12+</sup>                    | "GPSDOP"                    | **Read/Write capability**: readable and writable<br> GPS DOP (data degree of precision)|
8800| GPS_SPEED_REF <sup>12+</sup>              | "GPSSpeedRef"               | **Read/Write capability**: readable and writable<br> Unit used to express the movement speed of the GPS receiver.|
8801| GPS_SPEED <sup>12+</sup>                  | "GPSSpeed"                  | **Read/Write capability**: readable and writable<br> Movement speed of the GPS receiver.|
8802| GPS_TRACK_REF <sup>12+</sup>              | "GPSTrackRef"               | **Read/Write capability**: readable and writable<br> Reference of the movement direction of the GPS receiver.|
8803| GPS_TRACK <sup>12+</sup>                  | "GPSTrack"                  | **Read/Write capability**: readable and writable<br> Movement direction of the GPS receiver.|
8804| GPS_IMG_DIRECTION_REF <sup>12+</sup>      | "GPSImgDirectionRef"        | **Read/Write capability**: readable and writable<br> Reference of the direction of the image when it was captured.|
8805| GPS_IMG_DIRECTION <sup>12+</sup>          | "GPSImgDirection"           | **Read/Write capability**: readable and writable<br> Direction of the image when it was captured.|
8806| GPS_MAP_DATUM <sup>12+</sup>              | "GPSMapDatum"               | **Read/Write capability**: readable and writable<br> Geodetic survey data used by the GPS receiver.|
8807| GPS_DEST_LATITUDE_REF <sup>12+</sup>      | "GPSDestLatitudeRef"        | **Read/Write capability**: readable and writable<br> Whether the latitude of the destination point is north or south latitude.|
8808| GPS_DEST_LATITUDE <sup>12+</sup>          | "GPSDestLatitude"           | **Read/Write capability**: readable and writable<br> Latitude of the destination point.|
8809| GPS_DEST_LONGITUDE_REF <sup>12+</sup>     | "GPSDestLongitudeRef"       | **Read/Write capability**: readable and writable<br> Whether the longitude of the destination point is east or west longitude.|
8810| GPS_DEST_LONGITUDE <sup>12+</sup>         | "GPSDestLongitude"          | **Read/Write capability**: readable and writable<br> Longitude of the destination point.|
8811| GPS_DEST_BEARING_REF <sup>12+</sup>       | "GPSDestBearingRef"         | **Read/Write capability**: readable and writable<br> Reference of the bearing to the destination point.|
8812| GPS_DEST_BEARING <sup>12+</sup>           | "GPSDestBearing"            | **Read/Write capability**: readable and writable<br> Bearing to the destination point.|
8813| GPS_DEST_DISTANCE_REF <sup>12+</sup>      | "GPSDestDistanceRef"        | **Read/Write capability**: readable and writable<br> Unit used to express the distance to the destination point.|
8814| GPS_DEST_DISTANCE <sup>12+</sup>          | "GPSDestDistance"           | **Read/Write capability**: readable and writable<br> Distance to the destination point.|
8815| GPS_PROCESSING_METHOD <sup>12+</sup>      | "GPSProcessingMethod"       | **Read/Write capability**: readable and writable<br> String that records the name of the method used for positioning.|
8816| GPS_AREA_INFORMATION <sup>12+</sup>       | "GPSAreaInformation"        | **Read/Write capability**: readable and writable<br> String that records the name of the GPS area.|
8817| GPS_DATE_STAMP<sup>10+</sup>              | "GPSDateStamp"              | **Read/Write capability**: readable and writable<br> GPS date stamp.|
8818| GPS_DIFFERENTIAL <sup>12+</sup>           | "GPSDifferential"           | **Read/Write capability**: readable and writable<br> Whether differential correction is applied to the GPS receiver. It is critical to accurate location accuracy.|
8819| GPS_H_POSITIONING_ERROR <sup>12+</sup>    | "GPSHPositioningError"      | **Read/Write capability**: readable and writable<br> Horizontal positioning error, in meters.|
8820| ISO_SPEED_RATINGS<sup>9+</sup>            | "ISOSpeedRatings"           | **Read/Write capability**: readable and writable<br> ISO sensitivity or ISO speed, for example, 400.|
8821| PHOTOGRAPHIC_SENSITIVITY <sup>12+</sup>   | "PhotographicSensitivity"   | **Read/Write capability**: readable and writable<br> Sensitivity of the camera or input device when the image was captured.|
8822| OECF <sup>12+</sup>                       | "OECF"                      | **Read/Write capability**: readable and writable<br> Opto-Electric Conversion Function (OECF) specified in ISO 14524.|
8823| SENSITIVITY_TYPE<sup>10+</sup>            | "SensitivityType"           | **Read/Write capability**: readable and writable<br> Sensitivity type.|
8824| STANDARD_OUTPUT_SENSITIVITY<sup>10+</sup> | "StandardOutputSensitivity" | **Read/Write capability**: readable and writable<br> Standard output sensitivity.|
8825| RECOMMENDED_EXPOSURE_INDEX<sup>10+</sup>  | "RecommendedExposureIndex"  | **Read/Write capability**: readable and writable<br> Recommended exposure index.|
8826| ISO_SPEED<sup>10+</sup>                   | "ISOSpeedRatings"           | **Read/Write capability**: readable and writable<br> ISO speed.|
8827| ISO_SPEED_LATITUDE_YYY <sup>12+</sup>     | "ISOSpeedLatitudeyyy"       | **Read/Write capability**: readable and writable<br> ISO speed latitude yyy value of the camera or input device, which is defined in ISO 12232.|
8828| ISO_SPEED_LATITUDE_ZZZ <sup>12+</sup>     | "ISOSpeedLatitudezzz"       | **Read/Write capability**: readable and writable<br> ISO speed latitude zzz value of the camera or input device, which is defined in ISO 12232.|
8829| EXIF_VERSION <sup>12+</sup>               | "ExifVersion"               | **Read/Write capability**: readable and writable<br> Version of the supported EXIF standard.|
8830| DATE_TIME_ORIGINAL<sup>9+</sup>           | "DateTimeOriginal"          | **Read/Write capability**: readable and writable<br> Time when the original image data was generated, for example, 2022:09:06 15:48:00.|
8831| DATE_TIME_DIGITIZED <sup>12+</sup>        | "DateTimeDigitized"         | **Read/Write capability**: readable and writable<br> Date and time when the image was stored as digital data, in the format of YYYY:MM:DD HH:MM:SS.|
8832| OFFSET_TIME <sup>12+</sup>                | "OffsetTime"                | **Read/Write capability**: readable and writable<br> Time with an offset from UTC when the image was captured, in the format of ±HH:MM.|
8833| OFFSET_TIME_ORIGINAL <sup>12+</sup>       | "OffsetTimeOriginal"        | **Read/Write capability**: readable and writable<br> Time with an offset from UTC when the original image was created. It is critical for time-sensitive applications.|
8834| OFFSET_TIME_DIGITIZED <sup>12+</sup>      | "OffsetTimeDigitized"       | **Read/Write capability**: readable and writable<br> Time with an offset from UTC when the image was digitized. It helps to accurately adjust the timestamp.|
8835| COMPONENTS_CONFIGURATION <sup>12+</sup>   | "ComponentsConfiguration"   | **Read/Write capability**: readable and writable<br> Specific information about compressed data.|
8836| COMPRESSED_BITS_PER_PIXEL <sup>12+</sup>  | "CompressedBitsPerPixel"    | **Read/Write capability**: readable and writable<br> Number of bits per pixel. It is specific to compressed data.|
8837| SHUTTER_SPEED <sup>12+</sup>              | "ShutterSpeedValue"         | **Read/Write capability**: readable and writable<br> Shutter speed, expressed in Additive System of Photographic Exposure (APEX) values.|
8838| APERTURE_VALUE<sup>10+</sup>              | "ApertureValue"             | **Read/Write capability**: readable and writable<br> Lens aperture. An example in the correct format is 4/1.|
8839| BRIGHTNESS_VALUE <sup>12+</sup>           | "BrightnessValue"           | **Read/Write capability**: readable and writable<br> Value of brightness, expressed in APEX values.|
8840| EXPOSURE_BIAS_VALUE<sup>10+</sup>         | "ExposureBiasValue"         | **Read/Write capability**: readable and writable<br> Exposure bias.|
8841| MAX_APERTURE_VALUE <sup>12+</sup>         | "MaxApertureValue"          | **Read/Write capability**: readable and writable<br> Smallest F number of the lens.|
8842| SUBJECT_DISTANCE <sup>12+</sup>           | "SubjectDistance"           | **Read/Write capability**: readable and writable<br> Distance to the subject, in meters.|
8843| METERING_MODE<sup>10+</sup>               | "MeteringMode"              | **Read/Write capability**: readable and writable<br> Metering mode.|
8844| LIGHT_SOURCE<sup>10+</sup>                | "LightSource"               | **Read/Write capability**: readable and writable<br> Light source. An example value is **Fluorescent**.|
8845| FLASH <sup>10+</sup>                      | "Flash"                     | **Read/Write capability**: readable and writable<br> Flash status.|
8846| FOCAL_LENGTH <sup>10+</sup>               | "FocalLength"               | **Read/Write capability**: readable and writable<br> Focal length of the lens.|
8847| SUBJECT_AREA <sup>12+</sup>               | "SubjectArea"               | **Read/Write capability**: readable and writable<br> Location and area of the main subject in the entire scene.|
8848| MAKER_NOTE <sup>12+</sup>                 | "MakerNote"                 | **Read/Write capability**: readable and writable<br> Marker used by EXIF/DCF manufacturers to record any required information.<br>This field is read-only in API versions 12 to 19 and is readable and writable in API version 20 and later.|
8849| SCENE_POINTER <sup>12+</sup>              | "HwMnoteScenePointer"       | **Read/Write capability**: read-only<br> Pointer to the scene.|
8850| SCENE_VERSION <sup>12+</sup>              | "HwMnoteSceneVersion"       | **Read/Write capability**: read-only<br> Scene algorithm version.|
8851| SCENE_FOOD_CONF<sup>11+</sup>             | "HwMnoteSceneFoodConf"      | **Read/Write capability**: read-only<br> Photographing scene: food.|
8852| SCENE_STAGE_CONF<sup>11+</sup>            | "HwMnoteSceneStageConf"     | **Read/Write capability**: read-only<br> Photographing scene: stage.|
8853| SCENE_BLUE_SKY_CONF<sup>11+</sup>         | "HwMnoteSceneBlueSkyConf"   | **Read/Write capability**: read-only<br> Photographing scene: blue sky.|
8854| SCENE_GREEN_PLANT_CONF<sup>11+</sup>      | "HwMnoteSceneGreenPlantConf" | **Read/Write capability**: read-only<br> Photographing scene: green plant.|
8855| SCENE_BEACH_CONF<sup>11+</sup>            | "HwMnoteSceneBeachConf"     | **Read/Write capability**: read-only<br> Photographing scene: beach.|
8856| SCENE_SNOW_CONF<sup>11+</sup>             | "HwMnoteSceneSnowConf"      | **Read/Write capability**: read-only<br> Photographing scene: snow.|
8857| SCENE_SUNSET_CONF<sup>11+</sup>           | "HwMnoteSceneSunsetConf"    | **Read/Write capability**: read-only<br> Photographing scene: sunset.|
8858| SCENE_FLOWERS_CONF<sup>11+</sup>          | "HwMnoteSceneFlowersConf"   | **Read/Write capability**: read-only<br> Photographing scene: flowers.|
8859| SCENE_NIGHT_CONF<sup>11+</sup>            | "HwMnoteSceneNightConf"     | **Read/Write capability**: read-only<br> Photographing scene: night.|
8860| SCENE_TEXT_CONF<sup>11+</sup>             | "HwMnoteSceneTextConf"      | **Read/Write capability**: read-only<br> Photographing scene: text.|
8861| FACE_POINTER <sup>12+</sup>               | "HwMnoteFacePointer"        | **Read/Write capability**: read-only<br> Face pointer.|
8862| FACE_VERSION <sup>12+</sup>               | "HwMnoteFaceVersion"        | **Read/Write capability**: read-only<br> Facial recognition algorithm version.|
8863| FACE_COUNT<sup>11+</sup>                  | "HwMnoteFaceCount"          | **Read/Write capability**: read-only<br> Number of faces.|
8864| FACE_CONF <sup>12+</sup>                  | "HwMnoteFaceConf"           | **Read/Write capability**: read-only<br> Face confidence.|
8865| FACE_SMILE_SCORE <sup>12+</sup>           | "HwMnoteFaceSmileScore"     | **Read/Write capability**: read-only<br> Smile score of for faces.|
8866| FACE_RECT <sup>12+</sup>                  | "HwMnoteFaceRect"           | **Read/Write capability**: read-only<br> Face rectangle.|
8867| FACE_LEYE_CENTER <sup>12+</sup>           | "HwMnoteFaceLeyeCenter"     | **Read/Write capability**: read-only<br> Left eye centered.|
8868| FACE_REYE_CENTER <sup>12+</sup>           | "HwMnoteFaceReyeCenter"     | **Read/Write capability**: read-only<br> Right eye centered.|
8869| FACE_MOUTH_CENTER <sup>12+</sup>          | "HwMnoteFaceMouthCenter"    | **Read/Write capability**: read-only<br> Mouth centered.|
8870| CAPTURE_MODE <sup>10+</sup>               | "HwMnoteCaptureMode"        | **Read/Write capability**: readable and writable<br> Capture mode.|
8871| BURST_NUMBER <sup>12+</sup>               | "HwMnoteBurstNumber"        | **Read/Write capability**: read-only<br> Number of burst shooting times.|
8872| FRONT_CAMERA <sup>12+</sup>               | "HwMnoteFrontCamera"        | **Read/Write capability**: read-only<br> Whether the front camera is used to take a selfie.|
8873| ROLL_ANGLE <sup>11+</sup>                 | "HwMnoteRollAngle"          | **Read/Write capability**: read-only<br> Roll angle.|
8874| PITCH_ANGLE<sup>11+</sup>                 | "HwMnotePitchAngle"         | **Read/Write capability**: read-only<br> Pitch angle.|
8875| PHYSICAL_APERTURE <sup>10+</sup>          | "HwMnotePhysicalAperture"   | **Read/Write capability**: read-only<br> Physical aperture.|
8876| FOCUS_MODE<sup>11+</sup>                  | "HwMnoteFocusMode"          | **Read/Write capability**: read-only<br> Focus mode.|
8877| USER_COMMENT <sup>10+</sup>               | "UserComment"               | **Read/Write capability**: readable and writable<br> User comments.|
8878| SUBSEC_TIME <sup>12+</sup>                | "SubsecTime"                | **Read/Write capability**: readable and writable<br> Tag used to record fractions of seconds for the **DateTime** tag.|
8879| SUBSEC_TIME_ORIGINAL <sup>12+</sup>       | "SubsecTimeOriginal"        | **Read/Write capability**: readable and writable<br> Tag used to record fractions of seconds for the **DateTimeOriginal** tag.|
8880| SUBSEC_TIME_DIGITIZED <sup>12+</sup>      | "SubsecTimeDigitized"       | **Read/Write capability**: readable and writable<br> Tag used to record fractions of seconds for the **DateTimeDigitized** tag.|
8881| FLASHPIX_VERSION <sup>12+</sup>           | "FlashpixVersion"           | **Read/Write capability**: readable and writable<br> FlashPix format version supported by an FPXR file. It is used to enhance device compatibility.|
8882| COLOR_SPACE <sup>12+</sup>                | "ColorSpace"                | **Read/Write capability**: readable and writable<br> Color space information, which is usually recorded as a color space specifier.|
8883| PIXEL_X_DIMENSION <sup>10+</sup>          | "PixelXDimension"           | **Read/Write capability**: readable and writable<br> Pixel X dimension.|
8884| PIXEL_Y_DIMENSION<sup>10+</sup>           | "PixelYDimension"           | **Read/Write capability**: readable and writable<br> Pixel Y dimension.|
8885| RELATED_SOUND_FILE <sup>12+</sup>         | "RelatedSoundFile"          | **Read/Write capability**: readable and writable<br> Name of an audio file related to the image data.|
8886| FLASH_ENERGY <sup>12+</sup>               | "FlashEnergy"               | **Read/Write capability**: readable and writable<br> Strobe energy at the time the image was captured, in Beam Candle Power Seconds (BCPS).|
8887| SPATIAL_FREQUENCY_RESPONSE <sup>12+</sup> | "SpatialFrequencyResponse"  | **Read/Write capability**: readable and writable<br> Spatial frequency table of the camera or input device.|
8888| FOCAL_PLANE_X_RESOLUTION <sup>12+</sup>   | "FocalPlaneXResolution"     | **Read/Write capability**: readable and writable<br> Number of pixels in the image width (X) direction per FocalPlaneResolutionUnit.|
8889| FOCAL_PLANE_Y_RESOLUTION <sup>12+</sup>   | "FocalPlaneYResolution"     | **Read/Write capability**: readable and writable<br> Number of pixels in the image height (Y) direction per FocalPlaneResolutionUnit.|
8890| FOCAL_PLANE_RESOLUTION_UNIT <sup>12+</sup> | "FocalPlaneResolutionUnit"  | **Read/Write capability**: readable and writable<br> Unit for measuring FocalPlaneXResolution and FocalPlaneYResolution.|
8891| SUBJECT_LOCATION <sup>12+</sup>           | "SubjectLocation"           | **Read/Write capability**: readable and writable<br> Location of the main subject relative to the left edge.|
8892| EXPOSURE_INDEX <sup>12+</sup>             | "ExposureIndex"             | **Read/Write capability**: readable and writable<br> Exposure index selected at the time the image is captured.|
8893| SENSING_METHOD <sup>12+</sup>             | "SensingMethod"             | **Read/Write capability**: readable and writable<br> Type of the image sensor on the camera.|
8894| FILE_SOURCE <sup>12+</sup>                | "FileSource"                | **Read/Write capability**: readable and writable<br> Image source.|
8895| SCENE_TYPE<sup>9+</sup>                   | "SceneType"                 | **Read/Write capability**: readable and writable<br> Type of the scene, for example, portrait, scenery, motion, and night.|
8896| CFA_PATTERN <sup>12+</sup>                | "CFAPattern"                | **Read/Write capability**: readable and writable<br> Color Filter Array (CFA) geometric pattern of the image sensor.|
8897| CUSTOM_RENDERED <sup>12+</sup>            | "CustomRendered"            | **Read/Write capability**: readable and writable<br> Special processing on image data.|
8898| EXPOSURE_MODE <sup>12+</sup>              | "ExposureMode"              | **Read/Write capability**: readable and writable<br> Exposure mode set when the image was captured.|
8899| WHITE_BALANCE <sup>10+</sup>              | "WhiteBalance"              | **Read/Write capability**: readable and writable<br> White balance.|
8900| DIGITAL_ZOOM_RATIO <sup>12+</sup>         | "DigitalZoomRatio"          | **Read/Write capability**: readable and writable<br> Digital zoom ratio when the image was captured.|
8901| FOCAL_LENGTH_IN_35_MM_FILM <sup>10+</sup> | "FocalLengthIn35mmFilm"     | **Read/Write capability**: readable and writable<br> Focal length in 35mm film.|
8902| SCENE_CAPTURE_TYPE <sup>12+</sup>         | "SceneCaptureType"          | **Read/Write capability**: readable and writable<br> Type of the scene that was captured.|
8903| GAIN_CONTROL <sup>12+</sup>               | "GainControl"               | **Read/Write capability**: readable and writable<br> Degree of overall image gain adjustment.|
8904| CONTRAST <sup>12+</sup>                   | "Contrast"                  | **Read/Write capability**: readable and writable<br> Direction of contrast processing used by the camera.|
8905| SATURATION <sup>12+</sup>                 | "Saturation"                | **Read/Write capability**: readable and writable<br> Direction of saturation processing used by the camera.|
8906| SHARPNESS <sup>12+</sup>                  | "Sharpness"                 | **Read/Write capability**: readable and writable<br> Direction of sharpness processing used by the camera.|
8907| DEVICE_SETTING_DESCRIPTION <sup>12+</sup> | "DeviceSettingDescription"  | **Read/Write capability**: readable and writable<br> Information about the photographing conditions of a specific camera model.|
8908| SUBJECT_DISTANCE_RANGE <sup>12+</sup>     | "SubjectDistanceRange"      | **Read/Write capability**: readable and writable<br> Distance to the subject.|
8909| IMAGE_UNIQUE_ID <sup>12+</sup>            | "ImageUniqueID"             | **Read/Write capability**: readable and writable<br> Unique identifier assigned to each image.|
8910| CAMERA_OWNER_NAME <sup>12+</sup>          | "CameraOwnerName"           | **Read/Write capability**: readable and writable<br> Name of the camera owner.|
8911| BODY_SERIAL_NUMBER <sup>12+</sup>         | "BodySerialNumber"          | **Read/Write capability**: readable and writable<br> Serial number of the camera body.|
8912| LENS_SPECIFICATION <sup>12+</sup>         | "LensSpecification"         | **Read/Write capability**: readable and writable<br> Specifications of the lens.|
8913| LENS_MAKE <sup>12+</sup>                  | "LensMake"                  | **Read/Write capability**: readable and writable<br> Manufacturer of the lens.|
8914| LENS_MODEL <sup>12+</sup>                 | "LensModel"                 | **Read/Write capability**: readable and writable<br> Model of the lens.|
8915| LENS_SERIAL_NUMBER <sup>12+</sup>         | "LensSerialNumber"          | **Read/Write capability**: readable and writable<br> Serial number of the lens.|
8916| COMPOSITE_IMAGE <sup>12+</sup>            | "CompositeImage"            | **Read/Write capability**: readable and writable<br> Whether the image is a composite image.|
8917| SOURCE_IMAGE_NUMBER_OF_COMPOSITE_IMAGE <sup>12+</sup>   | "SourceImageNumberOfCompositeImage"       | **Read/Write capability**: readable and writable<br> Number of source images of the composite image.|
8918| SOURCE_EXPOSURE_TIMES_OF_COMPOSITE_IMAGE <sup>12+</sup> | "SourceExposureTimesOfCompositeImage"     | **Read/Write capability**: readable and writable<br> Exposure time of source images of the composite image.|
8919| GAMMA <sup>12+</sup>                      | "Gamma"                     | **Read/Write capability**: readable and writable<br> Gamma value.|
8920| DNG_VERSION <sup>12+</sup>                | "DNGVersion"                | **Read/Write capability**: readable and writable<br> DNG version. It encodes the DNG 4-tier version number.|
8921| DEFAULT_CROP_SIZE <sup>12+</sup>          | "DefaultCropSize"           | **Read/Write capability**: readable and writable<br> Size of the final image area, in raw image coordinates, taking into account extra pixels around the edges of the final image.|
8922| GIF_LOOP_COUNT <sup>12+</sup>             | "GIFLoopCount"              | **Read/Write capability**: read-only<br> Number of GIF loops. The value **0** means an infinite loop, and other values means the number of loops.|
8923| IS_XMAGE_SUPPORTED <sup>12+</sup> | "HwMnoteIsXmageSupported" | **Read/Write capability**: readable and writable<br>Whether XMAGE is supported.|
8924| XMAGE_MODE <sup>12+</sup> | "HwMnoteXmageMode" | **Read/Write capability**: readable and writable<br>XMAGE watermark mode.|
8925| XMAGE_LEFT <sup>12+</sup> | "HwMnoteXmageLeft" | **Read/Write capability**: readable and writable<br>X1 coordinate of the watermark region.|
8926| XMAGE_TOP <sup>12+</sup> | "HwMnoteXmageTop" | **Read/Write capability**: readable and writable<br>Y1 coordinate of the watermark region.|
8927| XMAGE_RIGHT <sup>12+</sup> | "HwMnoteXmageRight" | **Read/Write capability**: readable and writable<br>X2 coordinate of the watermark region.|
8928| XMAGE_BOTTOM <sup>12+</sup> | "HwMnoteXmageBottom" | **Read/Write capability**: readable and writable<br>Y2 coordinate of the watermark region.|
8929| CLOUD_ENHANCEMENT_MODE <sup>12+</sup> | "HwMnoteCloudEnhancementMode" | **Read/Write capability**: readable and writable<br>Cloud enhancement mode.|
8930| WIND_SNAPSHOT_MODE <sup>12+</sup> | "HwMnoteWindSnapshotMode" | **Read/Write capability**: read-only<br>Motion snapshot mode.|
8931
8932## FragmentMapPropertyKey<sup>13+</sup>
8933
8934Enumerates the fragment map information.
8935
8936**System capability**: SystemCapability.Multimedia.Image.Core
8937
8938| Name         | Value                   | Description                               |
8939| ------------- | --------------------- | ----------------------------------- |
8940| X_IN_ORIGINAL | "XInOriginal"         | X coordinate of the upper left corner of the fragment map in the original image.|
8941| Y_IN_ORIGINAL | "YInOriginal"         | Y coordinate of the upper left corner of the fragment map in the original image.|
8942| WIDTH         | "FragmentImageWidth"  | Width of the fragment map.                   |
8943| HEIGHT        | "FragmentImageHeight" | Height of the fragment map.                   |
8944
8945## ImageFormat<sup>9+</sup>
8946
8947Enumerates the image formats.
8948
8949**System capability**: SystemCapability.Multimedia.Image.Core
8950
8951| Name        |   Value  | Description                |
8952| ------------ | ------ | -------------------- |
8953| YCBCR_422_SP | 1000   | YCBCR422 semi-planar format.|
8954| JPEG         | 2000   | JPEG encoding format.      |
8955
8956## ComponentType<sup>9+</sup>
8957
8958Enumerates the color component types of images.
8959
8960**System capability**: SystemCapability.Multimedia.Image.ImageReceiver
8961
8962| Name |   Value  | Description       |
8963| ----- | ------ | ----------- |
8964| YUV_Y | 1      | Luminance component. |
8965| YUV_U | 2      | Chrominance component. |
8966| YUV_V | 3      | Chrominance component. |
8967| JPEG  | 4      | JPEG type.|
8968
8969## Component<sup>9+</sup>
8970
8971Describes the color components of an image.
8972
8973**System capability**: SystemCapability.Multimedia.Image.Core
8974
8975| Name         | Type                            | Read Only| Optional| Description        |
8976| ------------- | -------------------------------- | ---- | ---- | ------------ |
8977| componentType | [ComponentType](#componenttype9) | Yes  | No  | Color component type.  |
8978| rowStride     | number                           | Yes  | No  | Row stride. The camera preview stream data needs to be read by stride. For details, see [Solution to Screen Artifacts During Camera Preview](https://developer.huawei.com/consumer/en/doc/best-practices/bpta-deal-stride-solution).      |
8979| pixelStride   | number                           | Yes  | No  | Pixel stride.  |
8980| byteBuffer    | ArrayBuffer                      | Yes  | No  | Component buffer.|
8981
8982## DecodingDynamicRange<sup>12+</sup>
8983
8984Enumerates the desired dynamic range of an image during decoding.
8985
8986**System capability**: SystemCapability.Multimedia.Image.Core
8987
8988| Name         | Value      | Description        |
8989| ------------- | ----------| ------------ |
8990| AUTO          | 0    | The image is decoded based on the format. If the image is in HDR format, it is decoded based on the HDR content; otherwise, it is decoded based on the SDR content. The image source created by calling [CreateIncrementalSource](#imagecreateincrementalsource9) is decoded into SDR content. |
8991| SDR           | 1    | The image is decoded according to the standard dynamic range.  |
8992| HDR           | 2    | The image is decoded according to the high dynamic range. The image source created by calling [CreateIncrementalSource](#imagecreateincrementalsource9) is decoded into SDR content.    |
8993
8994## PackingDynamicRange<sup>12+</sup>
8995
8996Enumerates the desired dynamic range of an image during encoding.
8997
8998**System capability**: SystemCapability.Multimedia.Image.Core
8999
9000| Name         | Value      | Description        |
9001| ------------- | ----------| ------------ |
9002| AUTO          | 0    | Adaptive. The [pixelmap](#pixelmap7) is encoded based on the format. If the PixelMap is in HDR format, it is encoded based on the HDR content; otherwise, it is encoded based on the SDR content. |
9003| SDR           | 1    | The image is decoded according to the standard dynamic range.  |
9004
9005## CropAndScaleStrategy<sup>18+</sup>
9006
9007Enumerates the order of cropping and scaling.
9008
9009If the **cropAndScaleStrategy** parameter is not specified in [DecodingOptions](#decodingoptions7) and both **desiredRegion** and **desiredSize** are set, the final decoding result may vary slightly due to differences in decoding algorithms used for different image formats.
9010
9011For example, if the original image size is 200x200, and you specify **desiredSize:{width: 150, height: 150}, desiredRegion:{x: 0, y: 0, width: 100, height: 100}**, the expectation is to decode the top-left 1/4 region of the original image and then scale the pixelMap size to 150x150.
9012
9013For JPEG and WebP images (as well as some DNG images that decode a JPEG preview within the file and therefore are treated as JPEG format), the system first performs downsampling. For instance, it might downsample by 7/8 and then crop the region based on a 175x175 image size. As a result, the final cropped region will be slightly larger than the top-left 1/4 of the original image.
9014
9015For SVG images, which are vector-based and can be scaled without losing clarity, the system scales the image based on the ratio of **desiredSize** to the original image size and then crops the region. This results in a decoded region that may differ from the exact 1/4 region of the original image.
9016
9017To ensure consistent results when both **desiredRegion** and **desiredSize** are set, set the **cropAndScaleStrategy** parameter to **CROP_FIRST**.
9018
9019**System capability**: SystemCapability.Multimedia.Image.Core
9020
9021| Name         | Value      | Description        |
9022| ------------- | ----------| ------------ |
9023| SCALE_FIRST   | 1    | If both **desiredRegion** and **desiredSize** are specified, the image is first scaled based on **desiredSize** and then cropped based on **desiredRegion**.    |
9024| CROP_FIRST    | 2    | If both **desiredRegion** and **desiredSize** are specified, the image is first cropped based on **desiredRegion** and then scaled based on **desiredSize**.    |
9025
9026## HdrMetadataKey<sup>12+</sup>
9027
9028Enumerates the keys of HDR metadata used by [pixelmap](#pixelmap7).
9029
9030**System capability**: SystemCapability.Multimedia.Image.Core
9031
9032| Name         | Value      | Description        |
9033| ------------- | ----------| ------------ |
9034| HDR_METADATA_TYPE    | 0    | Metadata type used by [pixelmap](#pixelmap7). |
9035| HDR_STATIC_METADATA  | 1    | Static metadata.  |
9036| HDR_DYNAMIC_METADATA | 2    | Dynamic metadata.  |
9037| HDR_GAINMAP_METADATA | 3    | Metadata used by gain maps.  |
9038
9039## HdrMetadataType<sup>12+</sup>
9040
9041Enumerates the values available for **HDR_METADATA_TYPE** in [HdrMetadataKey](#hdrmetadatakey12).
9042
9043**System capability**: SystemCapability.Multimedia.Image.Core
9044
9045| Name         | Value      | Description        |
9046| ------------- | ----------| ------------ |
9047| NONE     | 0    | No metadata. |
9048| BASE     | 1    | Metadata used for base graphics.  |
9049| GAINMAP  | 2    | Metadata used for gain maps.  |
9050| ALTERNATE| 3    | Metadata used for synthesized HDR graphics.  |
9051
9052## HdrStaticMetadata<sup>12+</sup>
9053
9054Describes the static metadata keys, that is, the values available for **HDR_STATIC_METADATA** in [HdrMetadataKey](#hdrmetadatakey12).
9055
9056**System capability**: SystemCapability.Multimedia.Image.Core
9057
9058| Name         | Type      | Read Only| Optional| Description        |
9059| ------------- | ----------| -- | -- | ------------ |
9060| displayPrimariesX     | Array\<number>  | No| No| X coordinate of the three primary colors of the display device after normalization. The array length is 3. The unit is 0.00002. The value range is [0.0, 1.0]. |
9061| displayPrimariesY     | Array\<number>  | No| No| Y coordinate of the three primary colors of the display device after normalization. The array length is 3. The unit is 0.00002. The value range is [0.0, 1.0]. |
9062| whitePointX  | number  | No| No| X coordinate of the white point after normalization. The unit is 0.00002. The value range is [0.0, 1.0].  |
9063| whitePointY  | number   | No| No| Y coordinate of the white point after normalization. The unit is 0.00002. The value range is [0.0, 1.0].  |
9064| maxLuminance  | number  | No| No| Maximum luminance of the main monitor. The unit is 1, and the maximum value is 65535.  |
9065| minLuminance  | number   | No| No| Minimum luminance of the main monitor. The unit is 0.0001, and the maximum value is 6.55535.  |
9066| maxContentLightLevel  | number  | No| No| Maximum luminance of the displayed content. The unit is 1, and the maximum value is 65535.  |
9067| maxFrameAverageLightLevel  | number  | No| No| Maximum average luminance of the displayed content. The unit is 1, and the maximum value is 65535.|
9068
9069## GainmapChannel<sup>12+</sup>
9070
9071Describes the data content of a single channel of the gain map. For details, see ISO 21496-1.
9072
9073**System capability**: SystemCapability.Multimedia.Image.Core
9074
9075| Name         | Type      | Read Only| Optional| Description        |
9076| ------------- | ----------| -- | -- | ------------ |
9077| gainmapMax     | number   | No| No| Maximum value of the gain map. For details, see ISO 21496-1. |
9078| gainmapMin     | number   | No| No| Minimum value of the gain map. For details, see ISO 21496-1. |
9079| gamma  | number    | No| No| Gamma. For details, see ISO 21496-1.  |
9080| baseOffset  | number     | No| No| Offset of the base graphic. For details, see ISO 21496-1.  |
9081| alternateOffset  | number    | No| No| Offset of the alternative graphic that can be extracted. For details, see ISO 21496-1.   |
9082
9083## HdrGainmapMetadata<sup>12+</sup>
9084
9085Describes the metadata keys used by a gain map, that is, the values available for **HDR_GAINMAP_METADATA** in [HdrMetadataKey](#hdrmetadatakey12). For details, see ISO 21496-1.
9086
9087**System capability**: SystemCapability.Multimedia.Image.Core
9088
9089| Name         | Type      | Read Only| Optional| Description        |
9090| ------------- | ----------| -- | -- | ------------ |
9091| writerVersion     | number   | No| No| Version used by the metadata editor. |
9092| miniVersion     | number   | No| No| Minimum version that needs to be understood for metadata parsing. |
9093| gainmapChannelCount  | number    | No| No| Number of color channels of the gain map. When the value is 3, the metadata values of the RGB channels are different. When the value is 1, the metadata values of the RGB channels are the same. For details, see ISO 21496-1. |
9094| useBaseColorFlag  | boolean     | No| No| Whether to use the color space of the base graphic. For details, see ISO 21496-1. The value **true** means to use the color space of the base graphic, and **false** means the opposite.  |
9095| baseHeadroom  | number    | No| No|  Headroom of the base graphic, which means the additional brightness that can be added to the base graphic. For details, see ISO 21496-1.  |
9096| alternateHeadroom  | number     | No| No|  Headroom of the alternate graphic. For details, see ISO 21496-1. |
9097| channels  | Array<[GainmapChannel](#gainmapchannel12)> | No| No| Number of channels. The length is 3. For details, see ISO 21496-1.|
9098
9099## HdrMetadataValue<sup>12+</sup>
9100
9101type HdrMetadataValue = HdrMetadataType | HdrStaticMetadata | ArrayBuffer | HdrGainmapMetadata
9102
9103Describes the HDR metadata values used by a PixelMap, which corresponds to the values available for [HdrMetadataKey](#hdrmetadatakey12).
9104
9105**System capability**: SystemCapability.Multimedia.Image.Core
9106
9107| Type               | Description                                           |
9108| ------------------- | ----------------------------------------------- |
9109| [HdrMetadataType](#hdrmetadatatype12) | Metadata value corresponding to the **HDR_GAINMAP_METADATA** key in [HdrMetadataKey](#hdrmetadatakey12).|
9110| [HdrStaticMetadata](#hdrstaticmetadata12) | Metadata value corresponding to the **HDR_STATIC_METADATA** key in [HdrMetadataKey](#hdrmetadatakey12).|
9111| ArrayBuffer | Metadata value corresponding to the **HDR_DYNAMIC_METADATA** key in [HdrMetadataKey](#hdrmetadatakey12).|
9112| [HdrGainmapMetadata](#hdrgainmapmetadata12) | Metadata value corresponding to the **HDR_GAINMAP_METADATA** key in [HdrMetadataKey](#hdrmetadatakey12).|
9113
9114## AntiAliasingLevel<sup>12+</sup>
9115
9116Enumerates the anti-aliasing levels.
9117
9118**Atomic service API**: This API can be used in atomic services since API version 14.
9119
9120**System capability**: SystemCapability.Multimedia.Image.Core
9121
9122| Name                  |   Value  | Description             |
9123| ---------------------- | ------ | ----------------- |
9124| NONE                | 0      | Nearest neighbor interpolation.  |
9125| LOW                 | 1      | Bilinear interpolation.  |
9126| MEDIUM              | 2      | Bilinear interpolation with mipmap enabled. You are advised to use this value when zooming out an image.  |
9127| HIGH                | 3      | Cubic interpolation.  |
9128
9129## AllocatorType<sup>15+</sup>
9130
9131Enumerates the types of the memory used for image decoding.
9132
9133**System capability**: SystemCapability.Multimedia.Image.Core
9134
9135| Name        | Value  | Description                              |
9136| ------------ | ---- | ---------------------------------- |
9137| AUTO         | 0    | The system determines whether DMA memory or shared memory is used.    |
9138| DMA          | 1    | DMA memory is used.           |
9139| SHARE_MEMORY | 2    | Shared memory is used.|
9140
9141## Supplementary Information
9142
9143### SVG Tags
9144
9145The SVG tags are supported since API version 10. The used version is (SVG) 1.1, and the width and height of the SVG tag must be set. An XML declaration can be added to an SVG file and start with **<?xml**. The following tags are supported:
9146- a
9147- circla
9148- clipPath
9149- defs
9150- ellipse
9151- feBlend
9152- feColorMatrix
9153- feComposite
9154- feDiffuseLighting
9155- feDisplacementMap
9156- feDistantLight
9157- feFlood
9158- feGaussianBlur
9159- feImage
9160- feMorphology
9161- feOffset
9162- fePointLight
9163- feSpecularLighting
9164- feSpotLight
9165- feTurbulence
9166- filter
9167- g
9168- image
9169- line
9170- linearGradient
9171- mask
9172- path
9173- pattern
9174- polygon
9175- polyline
9176- radialGradient
9177- rect
9178- stop
9179- svg
9180- text
9181- textPath
9182- tspan
9183- use
9184
9185<!--no_check-->