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