1# @ohos.multimedia.sendableImage (基于Sendable对象的图片处理)
2
3本模块基于Sendable对象,提供图片处理效果,包括通过属性创建PixelMap、读取图像像素数据、读取区域内的图片数据等。
4
5> **说明:**
6>
7> 本模块首批接口从API version 12开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8
9## 导入模块
10
11```ts
12import { sendableImage } from '@kit.ImageKit';
13```
14
15## sendableImage.createPixelMap
16
17createPixelMap(colors: ArrayBuffer, options: image.InitializationOptions): Promise\<PixelMap>
18
19通过属性创建PixelMap,默认采用BGRA_8888格式处理数据,通过Promise返回结果。
20
21**系统能力:** SystemCapability.Multimedia.Image.Core
22
23**参数:**
24
25| 参数名  | 类型                                             | 必填 | 说明                                                             |
26| ------- | ------------------------------------------------ | ---- | ---------------------------------------------------------------- |
27| colors  | ArrayBuffer                                      | 是   | 默认按照BGRA_8888格式处理的颜色数组。                                        |
28| options | [InitializationOptions](js-apis-image.md#initializationoptions8) | 是   | 创建像素的属性,包括透明度,尺寸,缩略值,像素格式和是否可编辑。 |
29
30**返回值:**
31
32| 类型                             | 说明                                                                    |
33| -------------------------------- | ----------------------------------------------------------------------- |
34| Promise\<[PixelMap](#pixelmap)> | 返回Pixelmap。<br>当创建的pixelmap大小超过原图大小时,返回原图pixelmap大小。|
35
36**示例:**
37
38```ts
39import { image } from '@kit.ImageKit';
40import { BusinessError } from '@kit.BasicServicesKit';
41
42async function Demo() {
43    const color: ArrayBuffer = new ArrayBuffer(96); // 96为需要创建的像素buffer大小,取值为:height * width *4
44    let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
45    sendableImage.createPixelMap(color, opts).then((pixelMap: sendableImage.PixelMap) => {
46        console.info('Succeeded in creating pixelmap.');
47    }).catch((error: BusinessError) => {
48        console.error(`Failed to create pixelmap. code is ${error.code}, message is ${error.message}`);
49    })
50}
51```
52
53## sendableImage.createPixelMapFromParcel
54
55createPixelMapFromParcel(sequence: rpc.MessageSequence): PixelMap
56
57从MessageSequence中获取PixelMap。
58
59**系统能力:** SystemCapability.Multimedia.Image.Core
60
61**参数:**
62
63| 参数名                 | 类型                                                  | 必填 | 说明                                     |
64| ---------------------- | ----------------------------------------------------- | ---- | ---------------------------------------- |
65| sequence               | [rpc.MessageSequence](../apis-ipc-kit/js-apis-rpc.md#messagesequence9) | 是   | 保存有PixelMap信息的MessageSequence。      |
66
67**返回值:**
68
69| 类型                             | 说明                  |
70| -------------------------------- | --------------------- |
71| [PixelMap](#pixelmap) | 成功同步返回PixelMap对象,失败抛出异常。 |
72
73**错误码:**
74
75以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
76
77| 错误码ID | 错误信息 |
78| ------- | --------------------------------------------|
79| 62980096 | If the operation failed|
80| 62980097 | If the ipc error|
81| 62980115 | Invalid input parameter|
82| 62980105 | Failed to get the data|
83| 62980177 | Abnormal API environment|
84| 62980178 | Failed to create the PixelMap|
85| 62980179 | Abnormal buffer size|
86| 62980180 | FD mapping failed|
87| 62980246 | Failed to read the PixelMap|
88
89**示例:**
90
91```ts
92import { sendableImage } from '@kit.ImageKit';
93import { image } from '@kit.ImageKit';
94import { rpc } from '@kit.IPCKit';
95import { BusinessError } from '@kit.BasicServicesKit';
96
97class MySequence implements rpc.Parcelable {
98    pixel_map: sendableImage.PixelMap;
99    constructor(conPixelmap: sendableImage.PixelMap) {
100        this.pixel_map = conPixelmap;
101    }
102    marshalling(messageSequence: rpc.MessageSequence) {
103        this.pixel_map.marshalling(messageSequence);
104        return true;
105    }
106    unmarshalling(messageSequence: rpc.MessageSequence) {
107        try {
108            this.pixel_map = sendableImage.createPixelMapFromParcel(messageSequence);
109        } catch(e) {
110            let error = e as BusinessError;
111            console.error(`createPixelMapFromParcel error. code is ${error.code}, message is ${error.message}`);
112            return false;
113        }
114      return true;
115    }
116}
117async function Demo() {
118   const color: ArrayBuffer = new ArrayBuffer(96);
119   let bufferArr: Uint8Array = new Uint8Array(color);
120   for (let i = 0; i < bufferArr.length; i++) {
121      bufferArr[i] = 0x80;
122   }
123   let opts: image.InitializationOptions = {
124      editable: true,
125      pixelFormat: 4,
126      size: { height: 4, width: 6 },
127      alphaType: 3
128   }
129   let pixelMap: image.PixelMap | undefined = undefined;
130   sendableImage.createPixelMap(color, opts).then((srcPixelMap: image.PixelMap) => {
131      pixelMap = srcPixelMap;
132   })
133   if (pixelMap != undefined) {
134     // 序列化
135     let parcelable: MySequence = new MySequence(pixelMap);
136     let data: rpc.MessageSequence = rpc.MessageSequence.create();
137     data.writeParcelable(parcelable);
138
139     // 反序列化 rpc获取到data
140     let ret: MySequence = new MySequence(pixelMap);
141     data.readParcelable(ret);
142
143     // 获取到pixelmap
144     let unmarshPixelmap = ret.pixel_map;
145   }
146}
147```
148
149## sendableImage.createPixelMapFromSurface
150
151createPixelMapFromSurface(surfaceId: string, region: image.Region): Promise\<PixelMap>
152
153从Surface id创建一个PixelMap对象。
154
155**系统能力:** SystemCapability.Multimedia.Image.Core
156
157**参数:**
158
159| 参数名                 | 类型                 | 必填 | 说明                                     |
160| ---------------------- | -------------       | ---- | ---------------------------------------- |
161| surfaceId              | string              | 是   | 从[XComponent](../apis-arkui/arkui-ts/ts-basic-components-xcomponent.md)组件获取的surfaceId。|
162| region                 | [Region](../apis-image-kit/js-apis-image.md#region8)  | 是   | 裁剪的尺寸。                         |
163
164**返回值:**
165| 类型                             | 说明                  |
166| -------------------------------- | --------------------- |
167| Promise\<[PixelMap](#pixelmap)> | 成功同步返回PixelMap对象,失败抛出异常。 |
168
169**错误码:**
170
171以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
172
173| 错误码ID | 错误信息 |
174| ------- | --------------------------------------------|
175| 62980115 | Invalid input parameter|
176| 62980105 | Failed to get the data|
177| 62980178 | Failed to create the PixelMap|
178
179**示例:**
180
181```ts
182import { image } from '@kit.ImageKit';
183import { BusinessError } from '@kit.BasicServicesKit';
184
185async function Demo(surfaceId: string) {
186    let region: image.Region = { x: 0, y: 0, size: { height: 100, width: 100 } };
187    sendableImage.createPixelMapFromSurface(surfaceId, region).then(() => {
188        console.info('Succeeded in creating pixelmap from Surface');
189    }).catch((error: BusinessError) => {
190        console.error(`Failed to create pixelmap. code is ${error.code}, message is ${error.message}`);
191    });
192}
193```
194
195## sendableImage.createPixelMapSync
196
197createPixelMapSync(colors: ArrayBuffer, options: image.InitializationOptions): PixelMap
198
199通过属性创建PixelMap,同步返回PixelMap结果。
200
201**系统能力:** SystemCapability.Multimedia.Image.Core
202
203**参数:**
204
205| 参数名  | 类型                                             | 必填 | 说明                                                             |
206| ------- | ------------------------------------------------ | ---- | ---------------------------------------------------------------- |
207| colors  | ArrayBuffer                                      | 是   | BGRA_8888格式的颜色数组。                                        |
208| options | [InitializationOptions](js-apis-image.md#initializationoptions8) | 是   | 创建像素的属性,包括透明度,尺寸,缩略值,像素格式和是否可编辑。 |
209
210**返回值:**
211| 类型                             | 说明                  |
212| -------------------------------- | --------------------- |
213| [PixelMap](#pixelmap) | 成功同步返回PixelMap对象,失败抛出异常。 |
214
215**错误码:**
216
217以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
218
219| 错误码ID | 错误信息 |
220| ------- | --------------------------------------------|
221|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed|
222
223**示例:**
224
225```ts
226import { image } from '@kit.ImageKit';
227import { BusinessError } from '@kit.BasicServicesKit';
228
229async function Demo() {
230    const color: ArrayBuffer = new ArrayBuffer(96); // 96为需要创建的像素buffer大小,取值为:height * width *4
231    let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
232    let pixelMap : sendableImage.PixelMap = sendableImage.createPixelMapSync(color, opts);
233    return pixelMap;
234}
235```
236
237## sendableImage.convertFromPixelMap
238
239convertFromPixelMap(pixelMap: image.PixelMap): PixelMap
240
241通过image下的PixelMap创建出一个sendableImage下的PixelMap,同步返回PixelMap结果。原PixelMap的方法均不可再调用。
242
243**系统能力:** SystemCapability.Multimedia.Image.Core
244
245**参数:**
246
247| 参数名  | 类型                                             | 必填 | 说明                                                             |
248| ------- | ------------------------------------------------ | ---- | ---------------------------------------------------------------- |
249| pixelMap | [image.PixelMap](js-apis-image.md#pixelmap7) | 是   | image下的非sendable的PixelMap。 |
250
251**返回值:**
252| 类型                             | 说明                  |
253| -------------------------------- | --------------------- |
254| [PixelMap](#pixelmap) | 成功同步返回sendable的PixelMap对象,失败抛出异常。 |
255
256**错误码:**
257
258以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
259
260| 错误码ID | 错误信息 |
261| ------- | --------------------------------------------|
262|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed|
263
264**示例:**
265
266```ts
267import { image } from '@kit.ImageKit';
268import { BusinessError } from '@kit.BasicServicesKit';
269
270async function Demo() {
271    const color: ArrayBuffer = new ArrayBuffer(96); // 96为需要创建的像素buffer大小,取值为:height * width *4
272    let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
273    let pixelMap : image.PixelMap = image.createPixelMapSync(color, opts);
274    let sendablePixelMap : sendableImage.PixelMap = sendableImage.convertFromPixelMap(pixelMap);
275    return sendablePixelMap;
276}
277```
278
279## sendableImage.convertToPixelMap
280
281convertToPixelMap(pixelMap: PixelMap): image.PixelMap
282
283通过sendableImage下的PixelMap创建出一个image下的PixelMap,同步返回PixelMap结果。原PixelMap的方法均不可再调用。
284
285**系统能力:** SystemCapability.Multimedia.Image.Core
286
287**参数:**
288
289| 参数名  | 类型                                             | 必填 | 说明                                                             |
290| ------- | ------------------------------------------------ | ---- | ---------------------------------------------------------------- |
291| pixelMap | [PixelMap](#pixelmap) | 是   | sendableImage下的PixelMap |
292
293**返回值:**
294| 类型                             | 说明                  |
295| -------------------------------- | --------------------- |
296| [PixelMap](js-apis-image.md#pixelmap7) | 成功同步返回image下的非sendable的PixelMap对象,失败抛出异常。 |
297
298**错误码:**
299
300以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
301
302| 错误码ID | 错误信息 |
303| ------- | --------------------------------------------|
304|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed|
305
306**示例:**
307
308```ts
309import { image } from '@kit.ImageKit';
310import { BusinessError } from '@kit.BasicServicesKit';
311
312async function Demo() {
313    const color: ArrayBuffer = new ArrayBuffer(96); // 96为需要创建的像素buffer大小,取值为:height * width *4
314    let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
315    let sendablePixelMap : sendableImage.PixelMap = sendableImage.createPixelMapSync(color, opts);
316    let pixelMap : image.PixelMap = sendableImage.convertToPixelMap(sendablePixelMap);
317    return pixelMap;
318}
319```
320
321## PixelMap
322
323图像像素类,用于读取或写入图像数据以及获取图像信息。在调用PixelMap的方法前,需要先通过[createPixelMap](#sendableimagecreatepixelmap)创建一个PixelMap实例。目前pixelmap序列化大小最大128MB,超过会送显失败。大小计算方式为(宽\*高\*每像素占用字节数)。
324
325sendableImage下的PixelMap支持sendable属性,支持worker线程共享。sendableImage下的PixelMap,可以利用[Convert](#sendableimageconverttopixelmap)方法与image下的PixelMap进行互相转换。转换后,原对象的方法均不允许再调用,否则将报错501 无法调用接口。跨线程处理PixelMap时,需要考虑多线程问题。
326
327在调用PixelMap的方法前,需要先通过[sendableImage.createPixelMap](#sendableimagecreatepixelmap)构建一个PixelMap对象。
328
329### 属性
330
331**系统能力:** SystemCapability.Multimedia.Image.Core
332
333| 名称              | 类型    | 可读 | 可写 | 说明                       |
334| -----------------| ------- | ---- | ---- | -------------------------- |
335| isEditable        | boolean | 是   | 否   | 图像像素是否可被编辑。 <br>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
336| isStrideAlignment | boolean | 是   | 否   | 图像内存是否为DMA内存,DMA内存的PixelMap会做256字节内存对齐,行末会存在padding区域。 |
337
338### readPixelsToBuffer
339
340readPixelsToBuffer(dst: ArrayBuffer): Promise\<void>
341
342读取图像像素数据,结果写入ArrayBuffer里,使用Promise形式返回。指定BGRA_8888格式创建pixelmap,读取的像素数据与原数据保持一致。
343
344**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
345
346**系统能力:** SystemCapability.Multimedia.Image.Core
347
348**参数:**
349
350| 参数名 | 类型        | 必填 | 说明                                                                                                  |
351| ------ | ----------- | ---- | ----------------------------------------------------------------------------------------------------- |
352| dst    | ArrayBuffer | 是   | 缓冲区,函数执行结束后获取的图像像素数据写入到该内存区域内。缓冲区大小由[getPixelBytesNumber](#getpixelbytesnumber)接口获取。 |
353
354**返回值:**
355
356| 类型           | 说明                                            |
357| -------------- | ----------------------------------------------- |
358| Promise\<void> | Promise实例,用于获取结果,失败时返回错误信息。 |
359
360**示例:**
361
362```ts
363import { BusinessError } from '@kit.BasicServicesKit';
364
365async function Demo() {
366    const readBuffer: ArrayBuffer = new ArrayBuffer(96); // 96为需要创建的像素buffer大小,取值为:height * width *4
367    if (pixelMap != undefined) {
368        pixelMap.readPixelsToBuffer(readBuffer).then(() => {
369            console.info('Succeeded in reading image pixel data.'); // 符合条件则进入
370        }).catch((error: BusinessError) => {
371            console.error(`Failed to read image pixel data. code is ${error.code}, message is ${error.message}`);// 不符合条件则进入
372        })
373    }
374}
375```
376
377### readPixelsToBufferSync
378
379readPixelsToBufferSync(dst: ArrayBuffer): void
380
381以同步方法读取PixelMap到Buffer里。
382
383**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
384
385**系统能力:** SystemCapability.Multimedia.Image.Core
386
387**参数:**
388
389| 参数名   | 类型                 | 必填 | 说明                                                                                                  |
390| -------- | -------------------- | ---- | ----------------------------------------------------------------------------------------------------- |
391| dst      | ArrayBuffer          | 是   | 缓冲区,函数执行结束后获取的图像像素数据写入到该内存区域内。缓冲区大小由[getPixelBytesNumber](#getpixelbytesnumber)接口获取。 |
392
393**错误码:**
394
395以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
396
397| 错误码ID | 错误信息 |
398| ------- | --------------------------------------------|
399|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
400|  501    | Resource Unavailable |
401
402**示例:**
403
404```ts
405import { BusinessError } from '@kit.BasicServicesKit';
406
407async function Demo() {
408    const readBuffer: ArrayBuffer = new ArrayBuffer(96); // 96为需要创建的像素buffer大小,取值为:height * width *4
409    if (pixelMap != undefined) {
410        pixelMap.readPixelsToBufferSync(readBuffer);
411    }
412}
413```
414
415### readPixels
416
417readPixels(area: image.PositionArea): Promise\<void>
418
419读取区域内的图片数据,使用Promise形式返回。
420
421**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
422
423**系统能力:** SystemCapability.Multimedia.Image.Core
424
425**参数:**
426
427| 参数名 | 类型                           | 必填 | 说明                     |
428| ------ | ------------------------------ | ---- | ------------------------ |
429| area   | [PositionArea](js-apis-image.md#positionarea7) | 是   | 区域大小,根据区域读取。 |
430
431**返回值:**
432
433| 类型           | 说明                                                |
434| :------------- | :-------------------------------------------------- |
435| Promise\<void> | Promise实例,用于获取读取结果,失败时返回错误信息。 |
436
437**示例:**
438
439```ts
440import { image } from '@kit.ImageKit';
441import { BusinessError } from '@kit.BasicServicesKit';
442
443async function Demo() {
444    const area: image.PositionArea = {
445        pixels: new ArrayBuffer(8),
446        offset: 0,
447        stride: 8,
448        region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
449    };
450    if (pixelMap != undefined) {
451        pixelMap.readPixels(area).then(() => {
452            console.info('Succeeded in reading the image data in the area.'); //符合条件则进入
453        }).catch((error: BusinessError) => {
454            console.error(`Failed to read the image data in the area. code is ${error.code}, message is ${error.message}`);// 不符合条件则进入
455        })
456    }
457}
458```
459
460### readPixelsSync
461
462readPixelsSync(area: image.PositionArea): void
463
464读取区域内的图片数据并同步返回结果。
465
466**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
467
468**系统能力:** SystemCapability.Multimedia.Image.Core
469
470**参数:**
471
472| 参数名 | 类型                           | 必填 | 说明                     |
473| ------ | ------------------------------ | ---- | ------------------------ |
474| area   | [PositionArea](js-apis-image.md#positionarea7) | 是   | 区域大小,根据区域读取。 |
475
476**错误码:**
477
478以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
479
480| 错误码ID | 错误信息 |
481| ------- | --------------------------------------------|
482|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
483|  501    | Resource Unavailable |
484
485**示例:**
486
487```ts
488import { image } from '@kit.ImageKit';
489import { BusinessError } from '@kit.BasicServicesKit';
490
491async function Demo() {
492    const area : image.PositionArea = {
493        pixels: new ArrayBuffer(8),
494        offset: 0,
495        stride: 8,
496        region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
497    };
498    if (pixelMap != undefined) {
499        pixelMap.readPixelsSync(area);
500    }
501}
502```
503
504### writePixels
505
506writePixels(area: image.PositionArea): Promise\<void>
507
508将PixelMap写入指定区域内,使用Promise形式返回写入结果。
509
510**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
511
512**系统能力:** SystemCapability.Multimedia.Image.Core
513
514**参数:**
515
516| 参数名 | 类型                           | 必填 | 说明                 |
517| ------ | ------------------------------ | ---- | -------------------- |
518| area   | [PositionArea](js-apis-image.md#positionarea7) | 是   | 区域,根据区域写入。 |
519
520**返回值:**
521
522| 类型           | 说明                                                |
523| :------------- | :-------------------------------------------------- |
524| Promise\<void> | Promise实例,用于获取写入结果,失败时返回错误信息。 |
525
526**示例:**
527
528```ts
529import { image } from '@kit.ImageKit';
530import { BusinessError } from '@kit.BasicServicesKit';
531
532async function Demo() {
533    const area: image.PositionArea = {
534        pixels: new ArrayBuffer(8),
535        offset: 0,
536        stride: 8,
537        region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
538    };
539    let bufferArr: Uint8Array = new Uint8Array(area.pixels);
540    for (let i = 0; i < bufferArr.length; i++) {
541        bufferArr[i] = i + 1;
542    }
543    if (pixelMap != undefined) {
544        pixelMap.writePixels(area).then(() => {
545            console.info('Succeeded to write pixelmap into the specified area.');
546        }).catch((error: BusinessError) => {
547            console.error(`Failed to write pixelmap into the specified area. code is ${error.code}, message is ${error.message}`);
548        })
549    }
550}
551```
552
553### writePixelsSync
554
555writePixelsSync(area: image.PositionArea): void
556
557以同步方法将PixelMap写入指定区域内。
558
559**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
560
561**系统能力:** SystemCapability.Multimedia.Image.Core
562
563**参数:**
564
565| 参数名 | 类型                           | 必填 | 说明                 |
566| ------ | ------------------------------ | ---- | -------------------- |
567| area   | [PositionArea](js-apis-image.md#positionarea7) | 是   | 区域,根据区域写入。 |
568
569**错误码:**
570
571以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
572
573| 错误码ID | 错误信息 |
574| ------- | --------------------------------------------|
575|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
576|  501    | Resource Unavailable |
577
578**示例:**
579
580```ts
581import { image } from '@kit.ImageKit';
582import { BusinessError } from '@kit.BasicServicesKit';
583
584async function Demo() {
585    const area: image.PositionArea = {
586        pixels: new ArrayBuffer(8),
587        offset: 0,
588        stride: 8,
589        region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
590    };
591    let bufferArr: Uint8Array = new Uint8Array(area.pixels);
592    for (let i = 0; i < bufferArr.length; i++) {
593        bufferArr[i] = i + 1;
594    }
595    if (pixelMap != undefined) {
596        pixelMap.writePixelsSync(area);
597    }
598}
599```
600
601### writeBufferToPixels
602
603writeBufferToPixels(src: ArrayBuffer): Promise\<void>
604
605读取缓冲区中的图片数据,结果写入PixelMap中,使用Promise形式返回。
606
607**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
608
609**系统能力:** SystemCapability.Multimedia.Image.Core
610
611**参数:**
612
613| 参数名 | 类型        | 必填 | 说明           |
614| ------ | ----------- | ---- | -------------- |
615| src    | ArrayBuffer | 是   | 图像像素数据。 |
616
617**返回值:**
618
619| 类型           | 说明                                            |
620| -------------- | ----------------------------------------------- |
621| Promise\<void> | Promise实例,用于获取结果,失败时返回错误信息。 |
622
623**示例:**
624
625```ts
626import { BusinessError } from '@kit.BasicServicesKit';
627
628async function Demo() {
629    const color: ArrayBuffer = new ArrayBuffer(96); // 96为需要创建的像素buffer大小,取值为:height * width *4
630    let bufferArr: Uint8Array = new Uint8Array(color);
631    for (let i = 0; i < bufferArr.length; i++) {
632        bufferArr[i] = i + 1;
633    }
634    if (pixelMap != undefined) {
635        pixelMap.writeBufferToPixels(color).then(() => {
636            console.info("Succeeded in writing data from a buffer to a PixelMap.");
637        }).catch((error: BusinessError) => {
638            console.error(`Failed to write data from a buffer to a PixelMap. code is ${error.code}, message is ${error.message}`);
639        })
640    }
641}
642```
643
644### writeBufferToPixelsSync
645
646writeBufferToPixelsSync(src: ArrayBuffer): void
647
648读取缓冲区中的图片数据,结果写入PixelMap并同步返回结果。
649
650**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
651
652**系统能力:** SystemCapability.Multimedia.Image.Core
653
654**参数:**
655
656| 参数名 | 类型        | 必填 | 说明           |
657| ------ | ----------- | ---- | -------------- |
658| src    | ArrayBuffer | 是   | 图像像素数据。 |
659
660**错误码:**
661
662以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
663
664| 错误码ID | 错误信息 |
665| ------- | --------------------------------------------|
666|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
667|  501    | Resource Unavailable |
668
669**示例:**
670
671```ts
672import { BusinessError } from '@kit.BasicServicesKit';
673
674async function Demo() {
675    const color : ArrayBuffer = new ArrayBuffer(96);  //96为需要创建的像素buffer大小,取值为:height * width *4
676    let bufferArr : Uint8Array = new Uint8Array(color);
677    for (let i = 0; i < bufferArr.length; i++) {
678        bufferArr[i] = i + 1;
679    }
680    if (pixelMap != undefined) {
681        pixelMap.writeBufferToPixelsSync(color);
682    }
683}
684```
685
686### getImageInfo
687
688getImageInfo(): Promise\<image.ImageInfo>
689
690获取图像像素信息,使用Promise形式返回获取的图像像素信息。
691
692**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
693
694**系统能力:** SystemCapability.Multimedia.Image.Core
695
696**返回值:**
697
698| 类型                              | 说明                                                        |
699| --------------------------------- | ----------------------------------------------------------- |
700| Promise\<[ImageInfo](js-apis-image.md#imageinfo)> | Promise实例,用于异步获取图像像素信息,失败时返回错误信息。 |
701
702**示例:**
703
704```ts
705import { image } from '@kit.ImageKit';
706import { BusinessError } from '@kit.BasicServicesKit';
707
708async function Demo() {
709    if (pixelMap != undefined) {
710        pixelMap.getImageInfo().then((imageInfo: image.ImageInfo) => {
711            if (imageInfo != undefined) {
712                console.info("Succeeded in obtaining the image pixel map information."+ imageInfo.size.height);
713            }
714        }).catch((error: BusinessError) => {
715            console.error(`Failed to obtain the image pixel map information. code is ${error.code}, message is ${error.message}`);
716        })
717    }
718}
719```
720
721### getImageInfoSync
722
723getImageInfoSync(): image.ImageInfo
724
725以同步方法获取图像像素信息。
726
727**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
728
729**系统能力:** SystemCapability.Multimedia.Image.ImageSource
730
731**返回值:**
732
733| 类型                              | 说明                                                        |
734| --------------------------------- | ----------------------------------------------------------- |
735| [ImageInfo](js-apis-image.md#imageinfo)           | 图像像素信息                                                |
736
737**错误码:**
738
739以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
740
741| 错误码ID | 错误信息 |
742| ------- | --------------------------------------------|
743|  501    | Resource Unavailable |
744
745**示例:**
746
747```ts
748import { image } from '@kit.ImageKit';
749import { BusinessError } from '@kit.BasicServicesKit';
750
751async function Demo() {
752    if (pixelMap != undefined) {
753        let imageInfo : image.ImageInfo = pixelMap.getImageInfoSync();
754    }
755}
756```
757
758### getBytesNumberPerRow
759
760getBytesNumberPerRow(): number
761
762获取图像像素每行字节数。
763
764**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
765
766**系统能力:** SystemCapability.Multimedia.Image.Core
767
768**返回值:**
769
770| 类型   | 说明                 |
771| ------ | -------------------- |
772| number | 图像像素的行字节数。 |
773
774**示例:**
775
776```ts
777let rowCount: number = pixelMap.getBytesNumberPerRow();
778```
779
780### getPixelBytesNumber
781
782getPixelBytesNumber(): number
783
784获取图像像素的总字节数。
785
786**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
787
788**系统能力:** SystemCapability.Multimedia.Image.Core
789
790**返回值:**
791
792| 类型   | 说明                 |
793| ------ | -------------------- |
794| number | 图像像素的总字节数。 |
795
796**示例:**
797
798```ts
799let pixelBytesNumber: number = pixelMap.getPixelBytesNumber();
800```
801
802### getDensity
803
804getDensity():number
805
806获取当前图像像素的密度。
807
808**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
809
810**系统能力:** SystemCapability.Multimedia.Image.Core
811
812**返回值:**
813
814| 类型   | 说明            |
815| ------ | --------------- |
816| number | 图像像素的密度。|
817
818**示例:**
819
820```ts
821let getDensity: number = pixelMap.getDensity();
822```
823
824### opacity
825
826opacity(rate: number): Promise\<void>
827
828通过设置透明比率来让PixelMap达到对应的透明效果,使用Promise形式返回。
829
830**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
831
832**系统能力:** SystemCapability.Multimedia.Image.Core
833
834**参数:**
835
836| 参数名 | 类型   | 必填 | 说明                        |
837| ------ | ------ | ---- | --------------------------- |
838| rate   | number | 是   | 透明比率的值。|
839
840**返回值:**
841
842| 类型           | 说明                                            |
843| -------------- | ----------------------------------------------- |
844| Promise\<void> | Promise实例,用于获取结果,失败时返回错误信息。 |
845
846**示例:**
847
848```ts
849import { BusinessError } from '@kit.BasicServicesKit';
850
851async function Demo() {
852    let rate: number = 0.5;
853    if (pixelMap != undefined) {
854        pixelMap.opacity(rate).then(() => {
855            console.info('Succeeded in setting opacity.');
856        }).catch((err: BusinessError) => {
857            console.error(`Failed to set opacity. code is ${err.code}, message is ${err.message}`);
858        })
859    }
860}
861```
862
863### opacitySync
864
865opacitySync(rate: number): void
866
867设置PixelMap的透明比率,初始化PixelMap。
868
869**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
870
871**系统能力:** SystemCapability.Multimedia.Image.Core
872
873**参数:**
874
875| 参数名   | 类型                 | 必填 | 说明                           |
876| -------- | -------------------- | ---- | ------------------------------ |
877| rate     | number               | 是   | 透明比率的值。   |
878
879**错误码:**
880
881以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
882
883| 错误码ID | 错误信息 |
884| ------- | --------------------------------------------|
885|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
886|  501    | Resource Unavailable |
887
888**示例:**
889
890```ts
891import { BusinessError } from '@kit.BasicServicesKit';
892
893async function Demo() {
894    let rate : number = 0.5;
895    if (pixelMap != undefined) {
896        pixelMap.opacitySync(rate);
897    }
898}
899```
900
901### createAlphaPixelmap
902
903createAlphaPixelmap(): Promise\<PixelMap>
904
905根据Alpha通道的信息,来生成一个仅包含Alpha通道信息的PixelMap,可用于阴影效果,使用Promise形式返回。
906
907**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
908
909**系统能力:** SystemCapability.Multimedia.Image.Core
910
911**返回值:**
912
913| 类型                             | 说明                        |
914| -------------------------------- | --------------------------- |
915| Promise\<[PixelMap](#pixelmap)> | Promise实例,返回pixelmap。 |
916
917**示例:**
918
919```ts
920import { BusinessError } from '@kit.BasicServicesKit';
921
922async function Demo() {
923    if (pixelMap != undefined) {
924        pixelMap.createAlphaPixelmap().then((alphaPixelMap: sendableImage.PixelMap) => {
925            console.info('Succeeded in creating alpha pixelmap.');
926        }).catch((error: BusinessError) => {
927            console.error(`Failed to create alpha pixelmap. code is ${error.code}, message is ${error.message}`);
928        })
929    }
930}
931```
932
933### createAlphaPixelmapSync
934
935createAlphaPixelmapSync(): PixelMap
936
937根据Alpha通道的信息,生成一个仅包含Alpha通道信息的PixelMap,可用于阴影效果,同步返回PixelMap类型的结果。
938
939**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
940
941**系统能力:** SystemCapability.Multimedia.Image.Core
942
943**返回值:**
944
945| 类型                             | 说明                  |
946| -------------------------------- | --------------------- |
947| [PixelMap](#pixelmap) | 成功同步返回PixelMap对象,失败抛出异常。 |
948
949**错误码:**
950
951以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
952
953| 错误码ID | 错误信息 |
954| ------- | --------------------------------------------|
955|  401    | Parameter error. Possible causes: 1.Parameter verification failed |
956|  501    | Resource Unavailable |
957
958**示例:**
959
960```ts
961import { BusinessError } from '@kit.BasicServicesKit';
962
963async function Demo() {
964    let resPixelMap : sendableImage.PixelMap = pixelMap.createAlphaPixelmapSync();
965    return resPixelMap;
966}
967```
968
969### scale
970
971scale(x: number, y: number): Promise\<void>
972
973根据输入的宽高对图片进行缩放,使用Promise形式返回。
974
975**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
976
977**系统能力:** SystemCapability.Multimedia.Image.Core
978
979**参数:**
980
981| 参数名 | 类型   | 必填 | 说明                            |
982| ------ | ------ | ---- | ------------------------------- |
983| x      | number | 是   | 宽度的缩放倍数。|
984| y      | number | 是   | 高度的缩放倍数。|
985
986**返回值:**
987
988| 类型           | 说明                        |
989| -------------- | --------------------------- |
990| Promise\<void> | Promise实例,异步返回结果。 |
991
992**示例:**
993
994```ts
995import { BusinessError } from '@kit.BasicServicesKit';
996
997async function Demo() {
998    let scaleX: number = 2.0;
999    let scaleY: number = 1.0;
1000    if (pixelMap != undefined) {
1001        pixelMap.scale(scaleX, scaleY).then(() => {
1002            console.info('Succeeded in scaling pixelmap.');
1003        }).catch((err: BusinessError) => {
1004            console.error(`Failed to scale pixelmap. code is ${err.code}, message is ${err.message}`);
1005
1006        })
1007    }
1008}
1009```
1010
1011### scaleSync
1012
1013scaleSync(x: number, y: number): void
1014
1015以同步方法根据输入的宽高对图片进行缩放。
1016
1017**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1018
1019**系统能力:** SystemCapability.Multimedia.Image.Core
1020
1021**参数:**
1022
1023| 参数名 | 类型   | 必填 | 说明                            |
1024| ------ | ------ | ---- | ------------------------------- |
1025| x      | number | 是   | 宽度的缩放倍数。|
1026| y      | number | 是   | 高度的缩放倍数。|
1027
1028**错误码:**
1029
1030以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
1031
1032| 错误码ID | 错误信息 |
1033| ------- | --------------------------------------------|
1034|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
1035|  501    | Resource Unavailable |
1036
1037**示例:**
1038
1039```ts
1040import { BusinessError } from '@kit.BasicServicesKit';
1041
1042async function Demo() {
1043    let scaleX: number = 2.0;
1044    let scaleY: number = 1.0;
1045    if (pixelMap != undefined) {
1046        pixelMap.scaleSync(scaleX, scaleY);
1047    }
1048}
1049```
1050
1051### translate
1052
1053translate(x: number, y: number): Promise\<void>
1054
1055根据输入的坐标对图片进行位置变换,使用Promise形式返回。
1056
1057**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1058
1059**系统能力:** SystemCapability.Multimedia.Image.Core
1060
1061**参数:**
1062
1063| 参数名 | 类型   | 必填 | 说明        |
1064| ------ | ------ | ---- | ----------- |
1065| x      | number | 是   | 区域横坐标。|
1066| y      | number | 是   | 区域纵坐标。|
1067
1068**返回值:**
1069
1070| 类型           | 说明                        |
1071| -------------- | --------------------------- |
1072| Promise\<void> | Promise实例,异步返回结果。 |
1073
1074**示例:**
1075
1076```ts
1077import { BusinessError } from '@kit.BasicServicesKit';
1078
1079async function Demo() {
1080    let translateX: number = 50.0;
1081    let translateY: number = 10.0;
1082    if (pixelMap != undefined) {
1083        pixelMap.translate(translateX, translateY).then(() => {
1084            console.info('Succeeded in translating pixelmap.');
1085        }).catch((err: BusinessError) => {
1086            console.error(`Failed to translate pixelmap. code is ${err.code}, message is ${err.message}`);
1087        })
1088    }
1089}
1090```
1091
1092### translateSync
1093
1094translateSync(x: number, y: number): void
1095
1096根据输入的坐标对图片进行位置变换并同步返回结果。
1097
1098**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1099
1100**系统能力:** SystemCapability.Multimedia.Image.Core
1101
1102**参数:**
1103
1104| 参数名   | 类型                 | 必填 | 说明                            |
1105| -------- | -------------------- | ---- | ------------------------------- |
1106| x        | number               | 是   | 宽度的缩放倍数。|
1107| y        | number               | 是   | 高度的缩放倍数。|
1108
1109**错误码:**
1110
1111以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
1112
1113| 错误码ID | 错误信息 |
1114| ------- | --------------------------------------------|
1115|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
1116|  501    | Resource Unavailable |
1117
1118**示例:**
1119
1120```ts
1121import { BusinessError } from '@kit.BasicServicesKit';
1122
1123async function Demo() {
1124    let translateX : number = 50.0;
1125    let translateY : number = 10.0;
1126    if (pixelMap != undefined) {
1127        pixelMap.translateSync(translateX, translateY);
1128    }
1129}
1130```
1131
1132### rotate
1133
1134rotate(angle: number): Promise\<void>
1135
1136根据输入的角度对图片进行旋转,使用Promise形式返回。
1137
1138**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1139
1140**系统能力:** SystemCapability.Multimedia.Image.Core
1141
1142**参数:**
1143
1144| 参数名 | 类型   | 必填 | 说明                          |
1145| ------ | ------ | ---- | ----------------------------- |
1146| angle  | number | 是   | 图片旋转的角度。              |
1147
1148**返回值:**
1149
1150| 类型           | 说明                        |
1151| -------------- | --------------------------- |
1152| Promise\<void> | Promise实例,异步返回结果。 |
1153
1154**示例:**
1155
1156```ts
1157import { BusinessError } from '@kit.BasicServicesKit';
1158
1159async function Demo() {
1160    let angle: number = 90.0;
1161    if (pixelMap != undefined) {
1162        pixelMap.rotate(angle).then(() => {
1163            console.info('Succeeded in rotating pixelmap.');
1164        }).catch((err: BusinessError) => {
1165            console.error(`Failed to rotate pixelmap. code is ${err.code}, message is ${err.message}`);
1166        })
1167    }
1168}
1169```
1170
1171### rotateSync
1172
1173rotateSync(angle: number): void
1174
1175根据输入的角度对图片进行旋转并同步返回结果。
1176
1177**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1178
1179**系统能力:** SystemCapability.Multimedia.Image.Core
1180
1181**参数:**
1182
1183| 参数名   | 类型                 | 必填 | 说明                          |
1184| -------- | -------------------- | ---- | ----------------------------- |
1185| angle    | number               | 是   | 图片旋转的角度。              |
1186
1187**错误码:**
1188
1189以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
1190
1191| 错误码ID | 错误信息 |
1192| ------- | --------------------------------------------|
1193|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
1194|  501    | Resource Unavailable |
1195
1196**示例:**
1197
1198```ts
1199import { BusinessError } from '@kit.BasicServicesKit';
1200
1201async function Demo() {
1202    let angle : number = 90.0;
1203    if (pixelMap != undefined) {
1204        pixelMap.rotateSync(angle);
1205    }
1206}
1207```
1208
1209### flip
1210
1211flip(horizontal: boolean, vertical: boolean): Promise\<void>
1212
1213根据输入的条件对图片进行翻转,使用Promise形式返回。
1214
1215**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1216
1217**系统能力:** SystemCapability.Multimedia.Image.Core
1218
1219**参数:**
1220
1221| 参数名     | 类型    | 必填 | 说明      |
1222| ---------- | ------- | ---- | --------- |
1223| horizontal | boolean | 是   | 水平翻转。|
1224| vertical   | boolean | 是   | 垂直翻转。|
1225
1226**返回值:**
1227
1228| 类型           | 说明                        |
1229| -------------- | --------------------------- |
1230| Promise\<void> | Promise实例,异步返回结果。 |
1231
1232**示例:**
1233
1234```ts
1235import { BusinessError } from '@kit.BasicServicesKit';
1236
1237async function Demo() {
1238    let horizontal: boolean = true;
1239    let vertical: boolean = false;
1240    if (pixelMap != undefined) {
1241        pixelMap.flip(horizontal, vertical).then(() => {
1242            console.info('Succeeded in flipping pixelmap.');
1243        }).catch((err: BusinessError) => {
1244            console.error(`Failed to flip pixelmap. code is ${err.code}, message is ${err.message}`);
1245
1246        })
1247    }
1248}
1249```
1250
1251### flipSync
1252
1253flipSync(horizontal: boolean, vertical: boolean): void
1254
1255根据输入的条件对图片进行翻转并同步返回结果。
1256
1257**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1258
1259**系统能力:** SystemCapability.Multimedia.Image.Core
1260
1261**参数:**
1262
1263| 参数名     | 类型                 | 必填 | 说明                          |
1264| ---------- | -------------------- | ---- | ----------------------------- |
1265| horizontal | boolean              | 是   | 水平翻转。                    |
1266| vertical   | boolean              | 是   | 垂直翻转。                    |
1267
1268**错误码:**
1269
1270以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
1271
1272| 错误码ID | 错误信息 |
1273| ------- | --------------------------------------------|
1274|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
1275|  501    | Resource Unavailable |
1276
1277**示例:**
1278
1279```ts
1280import { BusinessError } from '@kit.BasicServicesKit';
1281
1282async function Demo() {
1283    let horizontal : boolean = true;
1284    let vertical : boolean = false;
1285    if (pixelMap != undefined) {
1286        pixelMap.flipSync(horizontal, vertical);
1287    }
1288}
1289```
1290
1291### crop
1292
1293crop(region: image.Region): Promise\<void>
1294
1295根据输入的尺寸对图片进行裁剪,使用Promise形式返回。
1296
1297**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1298
1299**系统能力:** SystemCapability.Multimedia.Image.Core
1300
1301**参数:**
1302
1303| 参数名 | 类型               | 必填 | 说明        |
1304| ------ | ------------------ | ---- | ----------- |
1305| region | [Region](../apis-image-kit/js-apis-image.md#region8) | 是   | 裁剪的尺寸。|
1306
1307**返回值:**
1308
1309| 类型           | 说明                        |
1310| -------------- | --------------------------- |
1311| Promise\<void> | Promise实例,异步返回结果。 |
1312
1313**示例:**
1314
1315```ts
1316import { image } from '@kit.ImageKit';
1317import { BusinessError } from '@kit.BasicServicesKit';
1318
1319async function Demo() {
1320    let region: image.Region = { x: 0, y: 0, size: { height: 100, width: 100 } };
1321    if (pixelMap != undefined) {
1322        pixelMap.crop(region).then(() => {
1323            console.info('Succeeded in cropping pixelmap.');
1324        }).catch((err: BusinessError) => {
1325            console.error(`Failed to crop pixelmap. code is ${err.code}, message is ${err.message}`);
1326
1327        });
1328    }
1329}
1330```
1331
1332### cropSync
1333
1334cropSync(region: image.Region): void
1335
1336根据输入的尺寸裁剪图片。
1337
1338**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1339
1340**系统能力:** SystemCapability.Multimedia.Image.Core
1341
1342**参数:**
1343
1344| 参数名   | 类型                 | 必填 | 说明                          |
1345| -------- | -------------------- | ---- | ----------------------------- |
1346| region   | [Region](../apis-image-kit/js-apis-image.md#region8)   | 是   | 裁剪的尺寸。                  |
1347
1348**错误码:**
1349
1350以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
1351
1352| 错误码ID | 错误信息 |
1353| ------- | --------------------------------------------|
1354|  401    | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
1355|  501    | Resource Unavailable |
1356
1357**示例:**
1358
1359```ts
1360import { image } from '@kit.ImageKit';
1361import { BusinessError } from '@kit.BasicServicesKit';
1362
1363async function Demo() {
1364    let region : image.Region = { x: 0, y: 0, size: { height: 100, width: 100 } };
1365    if (pixelMap != undefined) {
1366        pixelMap.cropSync(region);
1367    }
1368}
1369```
1370
1371### getColorSpace
1372
1373getColorSpace(): colorSpaceManager.ColorSpaceManager
1374
1375获取图像广色域信息。
1376
1377**系统能力:** SystemCapability.Multimedia.Image.Core
1378
1379**返回值:**
1380
1381| 类型                                | 说明             |
1382| ----------------------------------- | ---------------- |
1383| [colorSpaceManager.ColorSpaceManager](../apis-arkgraphics2d/js-apis-colorSpaceManager.md#colorspacemanager) | 图像广色域信息。 |
1384
1385**错误码:**
1386
1387以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
1388
1389| 错误码ID | 错误信息 |
1390| ------- | --------------------------------------------|
1391| 62980101| If the image data abnormal.            |
1392| 62980103| If the image data unsupport.             |
1393| 62980115| If the image parameter invalid.            |
1394
1395**示例:**
1396
1397```ts
1398async function Demo() {
1399    if (pixelMap != undefined) {
1400        let csm = pixelMap.getColorSpace();
1401    }
1402}
1403```
1404
1405### setColorSpace
1406
1407setColorSpace(colorSpace: colorSpaceManager.ColorSpaceManager): void
1408
1409设置图像广色域信息。
1410
1411**系统能力:** SystemCapability.Multimedia.Image.Core
1412
1413**参数:**
1414
1415| 参数名     | 类型                                | 必填 | 说明            |
1416| ---------- | ----------------------------------- | ---- | --------------- |
1417| colorSpace | [colorSpaceManager.ColorSpaceManager](../apis-arkgraphics2d/js-apis-colorSpaceManager.md#colorspacemanager) | 是   | 图像广色域信息。|
1418
1419**错误码:**
1420
1421以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
1422
1423| 错误码ID | 错误信息 |
1424| ------- | --------------------------------------------|
1425| 62980111| If the operation invalid.        |
1426| 62980115| If the image parameter invalid.             |
1427
1428**示例:**
1429
1430```ts
1431import { colorSpaceManager } from '@kit.ArkGraphics2D';
1432async function Demo() {
1433    let colorSpaceName = colorSpaceManager.ColorSpace.SRGB;
1434    let csm: colorSpaceManager.ColorSpaceManager = colorSpaceManager.create(colorSpaceName);
1435    if (pixelMap != undefined) {
1436        pixelMap.setColorSpace(csm);
1437    }
1438}
1439```
1440
1441### applyColorSpace
1442
1443applyColorSpace(targetColorSpace: colorSpaceManager.ColorSpaceManager): Promise\<void>
1444
1445根据输入的目标色彩空间对图像像素颜色进行色彩空间转换,使用Promise形式返回。
1446
1447**系统能力:** SystemCapability.Multimedia.Image.Core
1448
1449**参数:**
1450
1451| 参数名 | 类型               | 必填 | 说明        |
1452| ------ | ------------------ | ---- | ----------- |
1453| targetColorSpace | [colorSpaceManager.ColorSpaceManager](../apis-arkgraphics2d/js-apis-colorSpaceManager.md#colorspacemanager) | 是   | 目标色彩空间,支持SRGB、DCI_P3、DISPLAY_P3、ADOBE_RGB_1998。|
1454
1455**返回值:**
1456
1457| 类型           | 说明                        |
1458| -------------- | --------------------------- |
1459| Promise\<void> | Promise实例,异步返回结果。 |
1460
1461**错误码:**
1462
1463以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
1464
1465| 错误码ID | 错误信息 |
1466| ------- | ------------------------------------------|
1467| 401     | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
1468| 62980104| Failed to initialize the internal object. |
1469| 62980108| Failed to convert the color space.       |
1470| 62980115| Invalid image parameter.            |
1471
1472**示例:**
1473
1474```ts
1475import { colorSpaceManager } from '@kit.ArkGraphics2D';
1476import { BusinessError } from '@kit.BasicServicesKit';
1477
1478async function Demo() {
1479    let colorSpaceName = colorSpaceManager.ColorSpace.SRGB;
1480    let targetColorSpace: colorSpaceManager.ColorSpaceManager = colorSpaceManager.create(colorSpaceName);
1481    pixelMap.applyColorSpace(targetColorSpace).then(() => {
1482        console.info('Succeeded in applying color space for pixelmap object.');
1483    }).catch((error: BusinessError) => {
1484        console.error(`Failed to apply color space for pixelmap object. code is ${error.code}, message is ${error.message}`);
1485    })
1486}
1487```
1488
1489### marshalling
1490
1491marshalling(sequence: rpc.MessageSequence): void
1492
1493将PixelMap序列化后写入MessageSequence。
1494
1495**系统能力:** SystemCapability.Multimedia.Image.Core
1496
1497**参数:**
1498
1499| 参数名                 | 类型                                                  | 必填 | 说明                                     |
1500| ---------------------- | ------------------------------------------------------ | ---- | ---------------------------------------- |
1501| sequence               | [rpc.MessageSequence](../apis-ipc-kit/js-apis-rpc.md#messagesequence9)  | 是   | 新创建的MessageSequence。                 |
1502
1503**错误码:**
1504
1505以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
1506
1507| 错误码ID | 错误信息 |
1508| ------- | --------------------------------------------|
1509| 62980115 | Invalid image parameter.              |
1510| 62980097 | IPC error.             |
1511
1512**示例:**
1513```ts
1514import { sendableImage } from '@kit.ImageKit';
1515import { image } from '@kit.ImageKit';
1516import { rpc } from '@kit.IPCKit';
1517
1518class MySequence implements rpc.Parcelable {
1519    pixel_map: sendableImage.PixelMap;
1520    constructor(conPixelMap : sendableImage.PixelMap) {
1521        this.pixel_map = conPixelMap;
1522    }
1523    marshalling(messageSequence : rpc.MessageSequence) {
1524        this.pixel_map.marshalling(messageSequence);
1525        console.info('marshalling');
1526        return true;
1527    }
1528    unmarshalling(messageSequence : rpc.MessageSequence) {
1529      sendableImage.createPixelMap(new ArrayBuffer(96), {size: { height:4, width: 6}}).then((pixelParcel: sendableImage.PixelMap) => {
1530        pixelParcel.unmarshalling(messageSequence).then(async (pixelMap: sendableImage.PixelMap) => {
1531          this.pixel_map = pixelMap;
1532          pixelMap.getImageInfo().then((imageInfo: image.ImageInfo) => {
1533            console.info("unmarshalling information h:" + imageInfo.size.height + "w:" + imageInfo.size.width);
1534          })
1535        })
1536      });
1537      return true;
1538    }
1539}
1540async function Demo() {
1541   const color: ArrayBuffer = new ArrayBuffer(96);
1542   let bufferArr: Uint8Array = new Uint8Array(color);
1543   for (let i = 0; i < bufferArr.length; i++) {
1544      bufferArr[i] = 0x80;
1545   }
1546   let opts: image.InitializationOptions = {
1547      editable: true,
1548      pixelFormat: 4,
1549      size: { height: 4, width: 6 },
1550      alphaType: 3
1551   }
1552   let pixelMap: sendableImage.PixelMap | undefined = undefined;
1553   sendableImage.createPixelMap(color, opts).then((srcPixelMap: sendableImage.PixelMap) => {
1554      pixelMap = srcPixelMap;
1555   })
1556   if (pixelMap != undefined) {
1557    // 序列化
1558     let parcelable: MySequence = new MySequence(pixelMap);
1559     let data: rpc.MessageSequence = rpc.MessageSequence.create();
1560     data.writeParcelable(parcelable);
1561
1562    // 反序列化 rpc获取到data
1563     let ret: MySequence = new MySequence(pixelMap);
1564     data.readParcelable(ret);
1565   }
1566}
1567```
1568
1569### unmarshalling
1570
1571unmarshalling(sequence: rpc.MessageSequence): Promise\<PixelMap>
1572
1573从MessageSequence中获取PixelMap,
1574如需使用同步方式创建PixelMap可使用:[createPixelMapFromParcel](#sendableimagecreatepixelmapfromparcel)。
1575
1576**系统能力:** SystemCapability.Multimedia.Image.Core
1577
1578**参数:**
1579
1580| 参数名                 | 类型                                                  | 必填 | 说明                                     |
1581| ---------------------- | ----------------------------------------------------- | ---- | ---------------------------------------- |
1582| sequence               | [rpc.MessageSequence](../apis-ipc-kit/js-apis-rpc.md#messagesequence9) | 是   | 保存有PixelMap信息的MessageSequence。      |
1583
1584**返回值:**
1585
1586| 类型                             | 说明                  |
1587| -------------------------------- | --------------------- |
1588| Promise\<[PixelMap](#pixelmap)> | Promise实例,用于异步获取结果,失败时返回错误信息。 |
1589
1590**错误码:**
1591
1592以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
1593
1594| 错误码ID | 错误信息 |
1595| ------- | --------------------------------------------|
1596| 62980115 | Invalid image parameter.              |
1597| 62980097 | IPC error.              |
1598| 62980096 | The operation failed.         |
1599
1600**示例:**
1601
1602```ts
1603import { sendableImage } from '@kit.ImageKit';
1604import { image } from '@kit.ImageKit';
1605import { rpc } from '@kit.IPCKit';
1606
1607class MySequence implements rpc.Parcelable {
1608    pixel_map: sendableImage.PixelMap;
1609    constructor(conPixelMap: sendableImage.PixelMap) {
1610        this.pixel_map = conPixelMap;
1611    }
1612    marshalling(messageSequence: rpc.MessageSequence) {
1613        this.pixel_map.marshalling(messageSequence);
1614        console.info('marshalling');
1615        return true;
1616    }
1617    unmarshalling(messageSequence: rpc.MessageSequence) {
1618      sendableImage.createPixelMap(new ArrayBuffer(96), {size: { height:4, width: 6}}).then((pixelParcel : sendableImage.PixelMap) => {
1619        pixelParcel.unmarshalling(messageSequence).then(async (pixelMap : sendableImage.PixelMap) => {
1620          this.pixel_map = pixelMap;
1621          pixelMap.getImageInfo().then((imageInfo : image.ImageInfo) => {
1622            console.info("unmarshalling information h:" + imageInfo.size.height + "w:" + imageInfo.size.width);
1623          })
1624        })
1625      });
1626      return true;
1627    }
1628}
1629async function Demo() {
1630   const color: ArrayBuffer = new ArrayBuffer(96);
1631   let bufferArr: Uint8Array = new Uint8Array(color);
1632   for (let i = 0; i < bufferArr.length; i++) {
1633      bufferArr[i] = 0x80;
1634   }
1635   let opts: image.InitializationOptions = {
1636      editable: true,
1637      pixelFormat: 4,
1638      size: { height: 4, width: 6 },
1639      alphaType: 3
1640   }
1641   let pixelMap: sendableImage.PixelMap | undefined = undefined;
1642   sendableImage.createPixelMap(color, opts).then((srcPixelMap : sendableImage.PixelMap) => {
1643      pixelMap = srcPixelMap;
1644   })
1645   if (pixelMap != undefined) {
1646    // 序列化
1647     let parcelable: MySequence = new MySequence(pixelMap);
1648     let data : rpc.MessageSequence = rpc.MessageSequence.create();
1649     data.writeParcelable(parcelable);
1650
1651    // 反序列化 rpc获取到data
1652     let ret : MySequence = new MySequence(pixelMap);
1653     data.readParcelable(ret);
1654   }
1655}
1656```
1657
1658### release
1659
1660release():Promise\<void>
1661
1662释放PixelMap对象,使用Promise形式返回释放结果。
1663
1664**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1665
1666**系统能力:** SystemCapability.Multimedia.Image.Core
1667
1668**返回值:**
1669
1670| 类型           | 说明                            |
1671| -------------- | ------------------------------- |
1672| Promise\<void> | Promise实例,异步返回释放结果。 |
1673
1674**示例:**
1675
1676```ts
1677import { BusinessError } from '@kit.BasicServicesKit';
1678
1679async function Demo() {
1680    if (pixelMap != undefined) {
1681        pixelMap.release().then(() => {
1682            console.info('Succeeded in releasing pixelmap object.');
1683        }).catch((error: BusinessError) => {
1684            console.error(`Failed to release pixelmap object. code is ${error.code}, message is ${error.message}`);
1685        })
1686    }
1687}
1688```
1689
1690## Size
1691
1692表示图片尺寸。
1693继承自[lang.ISendable](../../arkts-utils/arkts-sendable.md#isendable)。
1694
1695**卡片能力:** 从API version 12开始,该接口支持在ArkTS卡片中使用。
1696
1697**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1698
1699**系统能力:** SystemCapability.Multimedia.Image.Core
1700
1701| 名称   | 类型   | 只读 | 可选 | 说明           |
1702| ------ | ------ | ---- | ---- | -------------- |
1703| height | number | 否   | 否   | 输出图片的高,单位:像素。 |
1704| width  | number | 否   | 否   | 输出图片的宽,单位:像素。 |
1705
1706## Region
1707
1708表示区域信息。
1709继承自[lang.ISendable](../../arkts-utils/arkts-sendable.md#isendable)。
1710
1711**卡片能力:** 从API version 12开始,该接口支持在ArkTS卡片中使用。
1712
1713**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1714
1715**系统能力:** SystemCapability.Multimedia.Image.Core
1716
1717| 名称 | 类型          | 只读 | 可选 | 说明         |
1718| ---- | ------------- | ---- | ---- | ------------ |
1719| size | [Size](#size) | 否   | 否   | 区域大小。   |
1720| x    | number        | 否   | 否   | 区域横坐标。 |
1721| y    | number        | 否   | 否   | 区域纵坐标。 |
1722
1723## sendableImage.createImageSource
1724
1725createImageSource(uri: string): ImageSource
1726
1727通过传入的uri创建图片源实例。
1728
1729
1730**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1731
1732**系统能力:** SystemCapability.Multimedia.Image.ImageSource
1733
1734**参数:**
1735
1736| 参数名 | 类型   | 必填 | 说明                               |
1737| ------ | ------ | ---- | ---------------------------------- |
1738| uri    | string | 是   | 图片路径,当前仅支持应用沙箱路径。</br>当前支持格式有:.jpg .png .gif .bmp .webp .dng [SVG](./js-apis-image.md#svg标签说明) .ico。 |
1739
1740**返回值:**
1741
1742| 类型                        | 说明                                         |
1743| --------------------------- | -------------------------------------------- |
1744| [ImageSource](#imagesource) | 返回ImageSource类实例,失败时返回undefined。 |
1745
1746**示例:**
1747
1748```ts
1749const context: Context = getContext(this);
1750const path: string = context.cacheDir + "/test.jpg";
1751const sendableImageSourceApi: sendableImage.ImageSource = sendableImage.createImageSource(path);
1752```
1753
1754## sendableImage.createImageSource
1755
1756createImageSource(fd: number): ImageSource
1757
1758通过传入文件描述符来创建图片源实例。
1759
1760**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1761
1762**系统能力:** SystemCapability.Multimedia.Image.ImageSource
1763
1764**参数:**
1765
1766| 参数名 | 类型   | 必填 | 说明          |
1767| ------ | ------ | ---- | ------------- |
1768| fd     | number | 是   | 文件描述符fd。|
1769
1770**返回值:**
1771
1772| 类型                        | 说明                                         |
1773| --------------------------- | -------------------------------------------- |
1774| [ImageSource](#imagesource) | 返回ImageSource类实例,失败时返回undefined。 |
1775
1776**示例:**
1777
1778```ts
1779import { fileIo as fs } from '@kit.CoreFileKit';
1780
1781const context: Context = getContext(this);
1782const path: string = context.cacheDir + "/test.jpg";
1783let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
1784const sendableImageSourceApi: sendableImage.ImageSource = sendableImage.createImageSource(file.fd);
1785```
1786
1787## sendableImage.createImageSource
1788
1789createImageSource(buf: ArrayBuffer): ImageSource
1790
1791通过缓冲区创建图片源实例。
1792
1793**卡片能力:** 从API version 12开始,该接口支持在ArkTS卡片中使用。
1794
1795**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1796
1797**系统能力:** SystemCapability.Multimedia.Image.ImageSource
1798
1799**参数:**
1800
1801| 参数名 | 类型        | 必填 | 说明             |
1802| ------ | ----------- | ---- | ---------------- |
1803| buf    | ArrayBuffer | 是   | 图像缓冲区数组。 |
1804
1805**返回值:**
1806
1807| 类型                        | 说明                                         |
1808| --------------------------- | -------------------------------------------- |
1809| [ImageSource](#imagesource) | 返回ImageSource类实例,失败时返回undefined。 |
1810
1811
1812**示例:**
1813
1814```ts
1815const buf: ArrayBuffer = new ArrayBuffer(96); // 96为需要创建的像素buffer大小,取值为:height * width *4
1816const sendableImageSourceApi: sendableImage.ImageSource = sendableImage.createImageSource(buf);
1817```
1818
1819## sendableImage.createImageReceiver
1820
1821createImageReceiver(size: image.Size, format: image.ImageFormat, capacity: number): ImageReceiver
1822
1823通过图片大小、图片格式、容量创建ImageReceiver实例。
1824
1825**系统能力:** SystemCapability.Multimedia.Image.ImageReceiver
1826
1827**参数:**
1828
1829| 参数名   | 类型   | 必填 | 说明                   |
1830| -------- | ------ | ---- | ---------------------- |
1831| size    | [image.Size](./js-apis-image.md#size)  | 是   | 图像的默认大小。       |
1832| format   | [image.ImageFormat](./js-apis-image.md#imageformat9) | 是   | 图像格式,取值为image.ImageFormat常量,目前仅支持 ImageFormat:JPEG。             |
1833| capacity | number | 是   | 同时访问的最大图像数。 |
1834
1835**返回值:**
1836
1837| 类型                             | 说明                                    |
1838| -------------------------------- | --------------------------------------- |
1839| [ImageReceiver](#imagereceiver) | 如果操作成功,则返回ImageReceiver实例。 |
1840
1841**错误码:**
1842
1843以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
1844
1845| 错误码ID | 错误信息 |
1846| ------- | --------------------------------------------|
1847| 401| Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types;   |
1848
1849**示例:**
1850
1851```ts
1852import { image } from '@kit.ImageKit';
1853
1854let size: image.Size = {
1855    height: 8192,
1856    width: 8
1857}
1858let receiver: sendableImage.ImageReceiver = sendableImage.createImageReceiver(size, image.ImageFormat.JPEG, 8);
1859```
1860
1861## ImageSource
1862
1863图片源类,用于获取图片相关信息。在调用ImageSource的方法前,需要先通过[createImageSource](#sendableimagecreateimagesource)构建一个ImageSource实例。
1864
1865
1866### createPixelMap
1867
1868createPixelMap(options?: image.DecodingOptions): Promise\<PixelMap>
1869
1870通过图片解码参数创建PixelMap对象。
1871
1872**卡片能力:** 从API version 12开始,该接口支持在ArkTS卡片中使用。
1873
1874**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1875
1876**系统能力:** SystemCapability.Multimedia.Image.ImageSource
1877
1878**参数:**
1879
1880| 参数名  | 类型                                 | 必填 | 说明       |
1881| ------- | ------------------------------------ | ---- | ---------- |
1882| options | [image.DecodingOptions](./js-apis-image.md#decodingoptions7) | 否   | 解码参数。 |
1883
1884**返回值:**
1885
1886| 类型                             | 说明                  |
1887| -------------------------------- | --------------------- |
1888| Promise\<[PixelMap]> | Promise实例,用于异步返回创建结果。 |
1889
1890**示例:**
1891
1892```ts
1893import { BusinessError } from '@kit.BasicServicesKit';
1894
1895const context: Context = getContext(this);
1896const path: string = context.cacheDir + "/test.jpg";
1897const sendableImageSourceApi: sendableImage.ImageSource = sendableImage.createImageSource(path);
1898sendableImageSourceApi.createPixelMap().then((pixelMap: sendableImage.PixelMap) => {
1899    console.info('Succeeded in creating pixelMap object through image decoding parameters.');
1900}).catch((error: BusinessError) => {
1901    console.error(`Failed to create pixelMap object through image decoding parameters. code ${error.code}, message is ${error.message}`);
1902})
1903```
1904
1905### release
1906
1907release(): Promise\<void>
1908
1909释放图片源实例,使用Promise形式返回结果。
1910release是线程不安全的。
1911
1912**系统能力:** SystemCapability.Multimedia.Image.ImageSource
1913
1914**返回值:**
1915
1916| 类型           | 说明                        |
1917| -------------- | --------------------------- |
1918| Promise\<void> | Promise实例,异步返回结果。 |
1919
1920**示例:**
1921
1922```ts
1923import { BusinessError } from '@kit.BasicServicesKit';
1924
1925const context: Context = getContext(this);
1926const path: string = context.cacheDir + "/test.jpg";
1927const sendableImageSourceApi: sendableImage.ImageSource = sendableImage.createImageSource(path);
1928sendableImageSourceApi.release().then(() => {
1929    console.info('Succeeded in releasing the image source instance.');
1930}).catch((error: BusinessError) => {
1931    console.error(`Failed to release the image source instance. code ${error.code}, message is ${error.message}`);
1932})
1933```
1934
1935## Image
1936
1937提供基本的图像操作,包括获取图像信息、读写图像数据。调用[readNextImage](#readnextimage)和[readLatestImage](#readlatestimage)接口时会返回image。
1938继承自[lang.ISendable](../../arkts-utils/arkts-sendable.md#isendable)。
1939
1940### 属性
1941
1942**系统能力:** SystemCapability.Multimedia.Image.Core
1943
1944| 名称     | 类型               | 只读 | 可选 | 说明                                               |
1945| -------- | ------------------ | ---- | ---- | -------------------------------------------------- |
1946| clipRect | [Region](#region) | 否   | 否   | 要裁剪的图像区域。                                 |
1947| size     | [Size](#size)      | 是   | 否   | 图像大小。如果image对象所存储的是相机预览流数据,即YUV图像数据,那么获取到的size中的宽高分别对应YUV图像的宽高; 如果image对象所存储的是相机拍照流数据,即JPEG图像,由于已经是编码后的文件,size中的宽等于JPEG文件大小,高等于1。image对象所存储的数据是预览流还是拍照流,取决于应用将receiver中的surfaceId传给相机的previewOutput还是captureOutput。相机预览与拍照最佳实践请参考[双路预览(ArkTS)](../../media/camera/camera-dual-channel-preview.md)与[拍照实现方案(ArkTS)](../../media/camera/camera-shooting-case.md)。                                         |
1948| format   | number             | 是   | 否   | 图像格式,参考[OH_NativeBuffer_Format](../apis-arkgraphics2d/_o_h___native_buffer.md#oh_nativebuffer_format)。 |
1949| timestamp<sup>12+</sup> | number         | 是      | 否   | 图像时间戳。时间戳以纳秒为单位,通常是单调递增的。时间戳的具体含义和基准取决于图像的生产者,在相机预览/拍照场景,生产者就是相机。来自不同生产者的图像的时间戳可能有不同的含义和基准,因此可能无法进行比较。如果要获取某张照片的生成时间,可以通过[getImageProperty](js-apis-image.md#getimageproperty11)接口读取相关的EXIF信息。|
1950
1951### getComponent
1952
1953getComponent(componentType: image.ComponentType): Promise\<image.Component>
1954
1955根据图像的组件类型从图像中获取组件缓存并使用Promise方式返回结果。
1956getComponent是线程不安全的。
1957
1958**系统能力:** SystemCapability.Multimedia.Image.Core
1959
1960**参数:**
1961
1962| 参数名        | 类型                             | 必填 | 说明             |
1963| ------------- | -------------------------------- | ---- | ---------------- |
1964| componentType | [image.ComponentType](./js-apis-image.md#componenttype9) | 是   | 图像的组件类型。 |
1965
1966**返回值:**
1967
1968| 类型                              | 说明                              |
1969| --------------------------------- | --------------------------------- |
1970| Promise<[image.Component](./js-apis-image.md#component9)> | Promise实例,用于异步返回组件缓冲区。 |
1971
1972**示例:**
1973
1974```ts
1975import { BusinessError } from '@kit.BasicServicesKit';
1976import { image } from '@kit.ImageKit';
1977
1978async function Demo() {
1979  let size: image.Size = {
1980    height: 8192,
1981    width: 8
1982  }
1983  let receiver: sendableImage.ImageReceiver = sendableImage.createImageReceiver(size, image.ImageFormat.JPEG, 8);
1984  let img = await receiver.readNextImage();
1985  img.getComponent(4).then((component: image.Component) => {
1986    console.info('getComponent succeeded.');
1987  }).catch((error: BusinessError) => {
1988    console.error(`getComponent failed code ${error.code}, message is ${error.message}`);
1989  })
1990}
1991```
1992
1993### release
1994
1995release(): Promise\<void>
1996
1997释放当前图像并使用Promise方式返回结果。
1998
1999在接收另一个图像前必须先释放对应资源。release是线程不安全的。
2000
2001
2002**系统能力:** SystemCapability.Multimedia.Image.Core
2003
2004**返回值:**
2005
2006| 类型           | 说明                  |
2007| -------------- | --------------------- |
2008| Promise\<void> | promise返回操作结果。 |
2009
2010**示例:**
2011
2012```ts
2013import { BusinessError } from '@kit.BasicServicesKit';
2014import { image } from '@kit.ImageKit';
2015
2016async function Demo() {
2017  let size: image.Size = {
2018    height: 8192,
2019    width: 8
2020  }
2021  let receiver: sendableImage.ImageReceiver = sendableImage.createImageReceiver(size, image.ImageFormat.JPEG, 8);
2022  let img = await receiver.readNextImage();
2023  img.release().then(() => {
2024    console.info('release succeeded.');
2025  }).catch((error: BusinessError) => {
2026    console.error(`release failed. code ${error.code}, message is ${error.message}`);
2027  })
2028}
2029```
2030
2031## ImageReceiver
2032
2033图像接收类,用于获取组件surface id,接收最新的图片和读取下一张图片,以及释放ImageReceiver实例。
2034
2035在调用以下方法前需要先创建ImageReceiver实例。
2036
2037### 属性
2038
2039**系统能力:** SystemCapability.Multimedia.Image.ImageReceiver
2040
2041| 名称     | 类型                         | 只读 | 可选 | 说明               |
2042| -------- | ---------------------------- | ---- | ---- | ------------------ |
2043| size     | [image.Size](./js-apis-image.md#size)                | 是   | 否   | 图片大小。         |
2044| capacity | number                       | 是   | 否   | 同时访问的图像数。 |
2045| format   | [image.ImageFormat](./js-apis-image.md#imageformat9) | 是   | 否   | 图像格式。         |
2046
2047### getReceivingSurfaceId
2048
2049getReceivingSurfaceId(): Promise\<string>
2050
2051用于获取一个surface id供Camera或其他组件使用。使用promise返回结果。
2052
2053**系统能力:** SystemCapability.Multimedia.Image.ImageReceiver
2054
2055**返回值:**
2056
2057| 类型             | 说明                 |
2058| ---------------- | -------------------- |
2059| Promise\<string> | 异步返回surface id。 |
2060
2061**示例:**
2062
2063```ts
2064import { BusinessError } from '@kit.BasicServicesKit';
2065import { image } from '@kit.ImageKit';
2066
2067let size: image.Size = {
2068    height: 8192,
2069    width: 8
2070}
2071let receiver: sendableImage.ImageReceiver = sendableImage.createImageReceiver(size, image.ImageFormat.JPEG, 8);
2072receiver.getReceivingSurfaceId().then((id: string) => {
2073    console.info('Succeeded in getting the ReceivingSurfaceId.');
2074}).catch((error: BusinessError) => {
2075    console.error(`Failed to get the ReceivingSurfaceId.code ${error.code}, message is ${error.message}`);
2076})
2077```
2078
2079### readLatestImage
2080
2081readLatestImage(): Promise\<Image>
2082
2083从ImageReceiver读取最新的图片,并使用promise返回结果。
2084
2085**注意**:此接口需要在[on](#on)回调触发后调用,才能正常的接收到数据。且此接口返回的[Image](#image)对象使用完毕后需要调用[release](#release-2)方法释放,释放后才可以继续接收新的数据。
2086
2087**系统能力:** SystemCapability.Multimedia.Image.ImageReceiver
2088
2089**返回值:**
2090
2091| 类型                      | 说明               |
2092| ------------------------- | ------------------ |
2093| Promise<[Image](#image)> | 异步返回最新图片。 |
2094
2095**示例:**
2096
2097```ts
2098import { BusinessError } from '@kit.BasicServicesKit';
2099import { image } from '@kit.ImageKit';
2100
2101let size: image.Size = {
2102    height: 8192,
2103    width: 8
2104}
2105let receiver: sendableImage.ImageReceiver = sendableImage.createImageReceiver(size, image.ImageFormat.JPEG, 8);
2106receiver.readLatestImage().then((img: image.Image) => {
2107    console.info('readLatestImage succeeded.');
2108}).catch((error: BusinessError) => {
2109    console.error(`readLatestImage failed. code ${error.code}, message is ${error.message}`);
2110})
2111```
2112
2113### readNextImage
2114
2115readNextImage(): Promise\<Image>
2116
2117从ImageReceiver读取下一张图片,并使用promise返回结果。
2118
2119**注意**:此接口需要在[on](#on)回调触发后调用,才能正常的接收到数据。且此接口返回的[Image](#image)对象使用完毕后需要调用[release](#release-2)方法释放,释放后才可以继续接收新的数据。
2120
2121**系统能力:** SystemCapability.Multimedia.Image.ImageReceiver
2122
2123**返回值:**
2124
2125| 类型                      | 说明                 |
2126| ------------------------- | -------------------- |
2127| Promise<[Image](#image)> | 异步返回下一张图片。 |
2128
2129**示例:**
2130
2131```ts
2132import { BusinessError } from '@kit.BasicServicesKit';
2133import { image } from '@kit.ImageKit';
2134
2135let size: image.Size = {
2136    height: 8192,
2137    width: 8
2138}
2139let receiver: sendableImage.ImageReceiver = sendableImage.createImageReceiver(size, image.ImageFormat.JPEG, 8);
2140receiver.readNextImage().then((img: image.Image) => {
2141    console.info('readNextImage succeeded.');
2142}).catch((error: BusinessError) => {
2143    console.error(`readNextImage failed. code ${error.code}, message is ${error.message}`);
2144})
2145```
2146
2147### on
2148
2149on(type: 'imageArrival', callback: AsyncCallback\<void>): void
2150
2151接收图片时注册回调。
2152
2153**系统能力:** SystemCapability.Multimedia.Image.ImageReceiver
2154
2155**参数:**
2156
2157| 参数名   | 类型                 | 必填 | 说明                                                   |
2158| -------- | -------------------- | ---- | ------------------------------------------------------ |
2159| type     | string               | 是   | 注册事件的类型,固定为'imageArrival',接收图片时触发。 |
2160| callback | AsyncCallback\<void> | 是   | 注册的事件回调。                                       |
2161
2162**示例:**
2163
2164```ts
2165import { BusinessError } from '@kit.BasicServicesKit';
2166import { image } from '@kit.ImageKit';
2167
2168let size: image.Size = {
2169    height: 8192,
2170    width: 8
2171}
2172let receiver: sendableImage.ImageReceiver = sendableImage.createImageReceiver(size, image.ImageFormat.JPEG, 8);
2173receiver.on('imageArrival', () => {
2174    // image arrival, do something.
2175})
2176```
2177
2178### release
2179
2180release(): Promise\<void>
2181
2182释放ImageReceiver实例并使用promise返回结果。
2183release是线程不安全的。
2184
2185**系统能力:** SystemCapability.Multimedia.Image.ImageReceiver
2186
2187**返回值:**
2188
2189| 类型           | 说明               |
2190| -------------- | ------------------ |
2191| Promise\<void> | 异步返回操作结果。 |
2192
2193**示例:**
2194
2195```ts
2196import { BusinessError } from '@kit.BasicServicesKit';
2197import { image } from '@kit.ImageKit';
2198
2199let size: image.Size = {
2200    height: 8192,
2201    width: 8
2202}
2203let receiver: sendableImage.ImageReceiver = sendableImage.createImageReceiver(size, image.ImageFormat.JPEG, 8);
2204receiver.release().then(() => {
2205    console.info('release succeeded.');
2206}).catch((error: BusinessError) => {
2207    console.error(`release failed. code ${error.code}, message is ${error.message}`);
2208})
2209```
2210