• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Interface (ImagePacker)
2<!--Kit: Image Kit-->
3<!--Subsystem: Multimedia-->
4<!--Owner: @aulight02-->
5<!--Designer: @liyang_bryan-->
6<!--Tester: @xchaosioda-->
7<!--Adviser: @zengyawen-->
8
9> **说明:**
10>
11> 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
12
13图片编码器类,用于图片压缩和编码。在调用ImagePacker的方法前,需要先通过[createImagePacker](arkts-apis-image-f.md#imagecreateimagepacker)构建一个ImagePacker实例,当前支持格式有:jpeg、webp、png、heif<sup>12+</sup>(不同硬件设备支持情况不同)。
14
15## 导入模块
16
17```ts
18import { image } from '@kit.ImageKit';
19```
20
21## 属性
22
23**系统能力:** SystemCapability.Multimedia.Image.ImagePacker
24
25| 名称             | 类型           | 只读 | 可选 | 说明                       |
26| ---------------- | -------------- | ---- | ---- | -------------------------- |
27| supportedFormats | Array\<string> | 是   | 否   | 图片编码支持的格式 jpeg、webp、png、heic<sup>12+</sup>(不同硬件设备支持情况不同)。 |
28
29## packToData<sup>13+</sup>
30
31packToData(source: ImageSource, options: PackingOption): Promise\<ArrayBuffer>
32
33图片压缩或重新编码,使用Promise形式返回结果。
34
35**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
36
37**系统能力:** SystemCapability.Multimedia.Image.ImagePacker
38
39**参数:**
40
41| 参数名 | 类型                            | 必填 | 说明           |
42| ------ | ------------------------------- | ---- | -------------- |
43| source | [ImageSource](arkts-apis-image-ImageSource.md)     | 是   | 编码的ImageSource。 |
44| options | [PackingOption](arkts-apis-image-i.md#packingoption) | 是   | 设置编码参数。 |
45
46**错误码:**
47
48以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
49
50| 错误码ID | 错误信息 |
51| ------- | --------------------------------------------|
52| 401 | If the parameter is invalid. |
53| 62980096| The operation failed. Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.              |
54| 62980101 | The image data is abnormal. |
55| 62980106 | The image data is too large. This status code is thrown when an error occurs during the process of checking size. |
56| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted.            |
57| 62980119 | Failed to encode the image. |
58| 62980120 | Add pixelmap out of range. |
59| 62980172 | Failed to encode icc. |
60| 62980252 | Failed to create surface. |
61
62**返回值:**
63
64| 类型                         | 说明                                          |
65| ---------------------------- | --------------------------------------------- |
66| Promise\<ArrayBuffer>        | Promise对象,返回压缩或编码后的数据。 |
67
68**示例:**
69
70```ts
71import { BusinessError } from '@kit.BasicServicesKit';
72
73async function PackToData(context : Context) {
74  // 此处'test.jpg'仅作示例,请开发者自行替换,否则imageSource会创建失败导致后续无法正常执行。
75  let filePath: string = context.filesDir + "/test.jpg";
76  const imageSourceObj: image.ImageSource = image.createImageSource(filePath);
77  let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }
78  const imagePackerObj: image.ImagePacker = image.createImagePacker();
79  imagePackerObj.packToData(imageSourceObj, packOpts)
80    .then((data: ArrayBuffer) => {
81      console.info('Succeeded in packing the image.');
82    }).catch((error: BusinessError) => {
83      console.error(`Failed to pack the image.code ${error.code},message is ${error.message}`);
84    })
85}
86```
87
88## packToData<sup>13+</sup>
89
90packToData(source: PixelMap, options: PackingOption): Promise\<ArrayBuffer>
91
92图片压缩或重新编码,使用Promise形式返回结果。
93
94> **注意:**
95> 接口如果返回401错误码,表明参数异常,可能是PixelMap对象被提前释放了。需要调用方排查,在该方法调用结束后再释放PixelMap对象。
96
97**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
98
99**系统能力:** SystemCapability.Multimedia.Image.ImagePacker
100
101**参数:**
102
103| 参数名 | 类型                            | 必填 | 说明               |
104| ------ | ------------------------------- | ---- | ------------------ |
105| source | [PixelMap](arkts-apis-image-PixelMap.md)           | 是   | 编码的PixelMap源。 |
106| options | [PackingOption](arkts-apis-image-i.md#packingoption) | 是   | 设置编码参数。     |
107
108**返回值:**
109
110| 类型                  | 说明                                         |
111| --------------------- | -------------------------------------------- |
112| Promise\<ArrayBuffer> | Promise对象,返回压缩或编码后的数据。|
113
114**错误码:**
115
116以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
117
118| 错误码ID | 错误信息 |
119| ------- | --------------------------------------------|
120| 401 | If the parameter is invalid. |
121| 62980096| The operation failed. Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.              |
122| 62980101 | The image data is abnormal. |
123| 62980106 | The image data is too large. This status code is thrown when an error occurs during the process of checking size. |
124| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted.            |
125| 62980119 | Failed to encode the image. |
126| 62980120 | Add pixelmap out of range. |
127| 62980172 | Failed to encode icc. |
128| 62980252 | Failed to create surface. |
129
130**示例:**
131
132```ts
133import { BusinessError } from '@kit.BasicServicesKit';
134
135async function PackToData() {
136  const color: ArrayBuffer = new ArrayBuffer(96); // 96为需要创建的像素buffer大小,取值为:height * width *4。
137  let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
138  image.createPixelMap(color, opts).then((pixelMap: image.PixelMap) => {
139    let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }
140    const imagePackerObj: image.ImagePacker = image.createImagePacker();
141    imagePackerObj.packToData(pixelMap, packOpts)
142      .then((data: ArrayBuffer) => {
143        console.info('Succeeded in packing the image.');
144      }).catch((error: BusinessError) => {
145      console.error(`Failed to pack the image.code ${error.code},message is ${error.message}`);
146    })
147  }).catch((error: BusinessError) => {
148    console.error(`Failed to create PixelMap.code ${error.code},message is ${error.message}`);
149  })
150}
151```
152
153## packing<sup>13+</sup>
154
155packing(picture: Picture, options: PackingOption): Promise\<ArrayBuffer>
156
157将图像压缩或重新编码,使用Promise形式返回结果。
158
159**系统能力:** SystemCapability.Multimedia.Image.ImagePacker
160
161**参数:**
162
163| 参数名           | 类型                                                 | 必填 | 说明                 |
164| ---------------- | ---------------------------------------------------- | ---- | -------------------- |
165| picture | [Picture](arkts-apis-image-Picture.md)                           | 是   | 编码的Picture对象。 |
166| options          | [PackingOption](arkts-apis-image-i.md#packingoption) | 是   | 设置编码参数。       |
167
168**返回值:**
169
170| 类型                  | 说明                                  |
171| --------------------- | ------------------------------------- |
172| Promise\<ArrayBuffer> | Promise对象,返回压缩或编码后的数据。 |
173
174**错误码:**
175
176以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
177
178| 错误码ID | 错误信息                                                     |
179| -------- | ------------------------------------------------------------ |
180| 401      | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
181| 7800301  | Encode failed.                                         |
182
183**示例:**
184
185```ts
186import { BusinessError } from '@kit.BasicServicesKit';
187
188async function Packing(context: Context) {
189  const resourceMgr = context.resourceManager;
190  const rawFile = await resourceMgr.getRawFileContent("test.jpg");
191  let ops: image.SourceOptions = {
192    sourceDensity: 98,
193  }
194  let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
195  let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap();
196  let pictureObj: image.Picture = image.createPicture(commodityPixelMap);
197  const imagePackerObj: image.ImagePacker = image.createImagePacker();
198  let funcName = "Packing";
199  if (imagePackerObj != null) {
200    let opts: image.PackingOption = {
201      format: "image/jpeg",
202      quality: 98,
203      bufferSize: 10,
204      desiredDynamicRange: image.PackingDynamicRange.AUTO,
205      needsPackProperties: true};
206    await imagePackerObj.packing(pictureObj, opts).then((data: ArrayBuffer) => {
207      console.info(funcName, 'Succeeded in packing the image.'+ data);
208    }).catch((error: BusinessError) => {
209      console.error(funcName, `Failed to pack the image.code ${error.code},message is ${error.message}`);
210    });
211  }
212}
213```
214
215## packToDataFromPixelmapSequence<sup>18+</sup>
216
217packToDataFromPixelmapSequence(pixelmapSequence: Array\<PixelMap>, options: PackingOptionsForSequence): Promise\<ArrayBuffer>
218
219将多个PixelMap编码成GIF数据。使用Promise形式返回结果。
220
221**系统能力:** SystemCapability.Multimedia.Image.ImagePacker
222
223**参数:**
224
225| 参数名           | 类型                                                      | 必填 | 说明                   |
226| ---------------- | --------------------------------------------------------- | ---- | ---------------------- |
227| pixelmapSequence | Array\<[PixelMap](arkts-apis-image-PixelMap.md)>                            | 是   | 待编码的PixelMap序列。 |
228| options          | [PackingOptionsForSequence](arkts-apis-image-i.md#packingoptionsforsequence18) | 是   | 动图编码参数。         |
229
230**返回值:**
231
232| 类型                  | 说明                            |
233| --------------------- | ------------------------------- |
234| Promise\<ArrayBuffer> | Promise对象,返回编码后的数据。 |
235
236**错误码:**
237
238以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[Image错误码](errorcode-image.md)。
239
240| 错误码ID | 错误信息                                                     |
241| -------- | ------------------------------------------------------------ |
242| 401      | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
243| 7800301  | Failed to encode image.                                      |
244
245**示例:**
246
247```ts
248import { BusinessError } from '@kit.BasicServicesKit';
249
250async function PackToDataFromPixelmapSequence(context : Context) {
251  const resourceMgr = context.resourceManager;
252  // 此处'moving_test.gif'仅作示例,请开发者自行替换。否则imageSource会创建失败,导致后续无法正常执行。
253  const fileData = await resourceMgr.getRawFileContent('moving_test.gif');
254  const color = fileData.buffer as ArrayBuffer;
255  let imageSource = image.createImageSource(color);
256  let pixelMapList = await imageSource.createPixelMapList();
257  let ops: image.PackingOptionsForSequence = {
258    frameCount: 3,  // 指定GIF编码中的帧数为3。
259    delayTimeList: [10, 10, 10],  // 指定GIF编码中3帧的延迟时间分别为100ms、100ms、100ms。
260    disposalTypes: [3, 2, 3], // 指定GIF编码中3帧的帧过渡模式分别为3(恢复到之前的状态)、2(恢复背景色)、3(恢复到之前的状态)。
261    loopCount: 0 // 指定GIF编码中循环次数为无限循环。
262  };
263  let Packer = image.createImagePacker();
264  Packer.packToDataFromPixelmapSequence(pixelMapList, ops)
265    .then((data: ArrayBuffer) => {
266      console.info('Succeeded in packing.');
267    }).catch((error: BusinessError) => {
268    console.error('Failed to packing.');
269  })
270}
271```
272
273## release
274
275release(callback: AsyncCallback\<void>): void
276
277释放图片编码实例,使用callback形式返回结果。
278
279ArkTS有内存回收机制,ImagePacker对象不调用release方法,内存最终也会由系统统一释放。但图片使用的内存往往较大,为尽快释放内存,建议应用在使用完成后主动调用release方法提前释放内存。
280
281**系统能力:** SystemCapability.Multimedia.Image.ImagePacker
282
283**参数:**
284
285| 参数名   | 类型                 | 必填 | 说明                           |
286| -------- | -------------------- | ---- | ------------------------------ |
287| callback | AsyncCallback\<void> | 是   | 回调函数,当释放图片编码实例成功,err为undefined,否则为错误对象。 |
288
289**示例:**
290
291```ts
292import { BusinessError } from '@kit.BasicServicesKit';
293
294async function Release() {
295  const imagePackerObj: image.ImagePacker = image.createImagePacker();
296  imagePackerObj.release((err: BusinessError)=>{
297    if (err) {
298      console.error(`Failed to release image packaging.code ${err.code},message is ${err.message}`);
299    } else {
300      console.info('Succeeded in releasing image packaging.');
301    }
302  })
303}
304```
305
306## release
307
308release(): Promise\<void>
309
310释放图片编码实例,使用Promise形式返回释放结果。
311
312ArkTS有内存回收机制,ImagePacker对象不调用release方法,内存最终也会由系统统一释放。但图片使用的内存往往较大,为尽快释放内存,建议应用在使用完成后主动调用release方法提前释放内存。
313
314**系统能力:** SystemCapability.Multimedia.Image.ImagePacker
315
316**返回值:**
317
318| 类型           | 说明                                                   |
319| -------------- | ------------------------------------------------------ |
320| Promise\<void> |  Promise对象。无返回结果的Promise对象。|
321
322**示例:**
323
324```ts
325import { BusinessError } from '@kit.BasicServicesKit';
326
327async function Release() {
328  const imagePackerObj: image.ImagePacker = image.createImagePacker();
329  imagePackerObj.release().then(() => {
330    console.info('Succeeded in releasing image packaging.');
331  }).catch((error: BusinessError) => {
332    console.error(`Failed to release image packaging.code ${error.code},message is ${error.message}`);
333  })
334}
335```
336
337## packToFile<sup>11+</sup>
338
339packToFile(source: ImageSource, fd: number, options: PackingOption, callback: AsyncCallback\<void>): void
340
341指定编码参数,将ImageSource直接编码进文件。使用callback形式返回结果。
342
343**系统能力:** SystemCapability.Multimedia.Image.ImagePacker
344
345**参数:**
346
347| 参数名   | 类型                            | 必填 | 说明                           |
348| -------- | ------------------------------- | ---- | ------------------------------ |
349| source   | [ImageSource](arkts-apis-image-ImageSource.md)     | 是   | 编码的ImageSource。                 |
350| fd       | number                          | 是   | 文件描述符。                   |
351| options   | [PackingOption](arkts-apis-image-i.md#packingoption) | 是   | 设置编码参数。                 |
352| callback | AsyncCallback\<void>            | 是   | 回调函数,当编码进文件成功,err为undefined,否则为错误对象。  |
353
354**错误码:**
355
356以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
357
358| 错误码ID | 错误信息 |
359| ------- | --------------------------------------------|
360| 62980096| The operation failed. Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.              |
361| 62980101 | The image data is abnormal. |
362| 62980106 | The image data is too large. This status code is thrown when an error occurs during the process of checking size. |
363| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted.            |
364| 62980115 | Invalid input parameter. |
365| 62980119 | Failed to encode the image. |
366| 62980120 | Add pixelmap out of range. |
367| 62980172 | Failed to encode icc. |
368| 62980252 | Failed to create surface. |
369
370**示例:**
371
372```ts
373import { BusinessError } from '@kit.BasicServicesKit';
374import { fileIo as fs } from '@kit.CoreFileKit';
375
376async function PackToFile(context : Context) {
377  // 此处'test.png'仅作示例,请开发者自行替换,否则imageSource会创建失败导致后续无法正常执行。
378  const path: string = context.filesDir + "/test.png";
379  const imageSourceObj: image.ImageSource = image.createImageSource(path);
380  let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 };
381  const filePath: string = context.filesDir + "/image_source.jpg";
382  let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
383  const imagePackerObj: image.ImagePacker = image.createImagePacker();
384  imagePackerObj.packToFile(imageSourceObj, file.fd, packOpts, (err: BusinessError) => {
385    if (err) {
386      console.error(`Failed to pack the image to file.code ${err.code},message is ${err.message}`);
387    } else {
388      console.info('Succeeded in packing the image to file.');
389    }
390  })
391}
392```
393
394## packToFile<sup>11+</sup>
395
396packToFile (source: ImageSource, fd: number, options: PackingOption): Promise\<void>
397
398指定编码参数,将ImageSource直接编码进文件。使用Promise形式返回结果。
399
400**系统能力:** SystemCapability.Multimedia.Image.ImagePacker
401
402**参数:**
403
404| 参数名 | 类型                            | 必填 | 说明           |
405| ------ | ------------------------------- | ---- | -------------- |
406| source | [ImageSource](arkts-apis-image-ImageSource.md)     | 是   | 编码的ImageSource。 |
407| fd     | number                          | 是   | 文件描述符。   |
408| options | [PackingOption](arkts-apis-image-i.md#packingoption) | 是   | 设置编码参数。 |
409
410**返回值:**
411
412| 类型           | 说明                              |
413| -------------- | --------------------------------- |
414| Promise\<void> |  Promise对象。无返回结果的Promise对象。 |
415
416**错误码:**
417
418以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
419
420| 错误码ID | 错误信息 |
421| ------- | --------------------------------------------|
422| 62980096| The operation failed. Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.              |
423| 62980101 | The image data is abnormal. |
424| 62980106 | The image data is too large. This status code is thrown when an error occurs during the process of checking size. |
425| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted.            |
426| 62980115 | Invalid input parameter. |
427| 62980119 | Failed to encode the image. |
428| 62980120 | Add pixelmap out of range. |
429| 62980172 | Failed to encode icc. |
430| 62980252 | Failed to create surface. |
431
432**示例:**
433
434```ts
435import { BusinessError } from '@kit.BasicServicesKit';
436import { fileIo as fs } from '@kit.CoreFileKit';
437
438async function PackToFile(context : Context) {
439  // 此处'test.png'仅作示例,请开发者自行替换,否则imageSource会创建失败导致后续无法正常执行。
440  const path: string = context.filesDir + "/test.png";
441  const imageSourceObj: image.ImageSource = image.createImageSource(path);
442  let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 };
443  const filePath: string = context.filesDir + "/image_source.jpg";
444  let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
445  const imagePackerObj: image.ImagePacker = image.createImagePacker();
446  imagePackerObj.packToFile(imageSourceObj, file.fd, packOpts).then(() => {
447    console.info('Succeeded in packing the image to file.');
448  }).catch((error: BusinessError) => {
449    console.error(`Failed to pack the image to file.code ${error.code},message is ${error.message}`);
450  })
451}
452```
453
454## packToFile<sup>11+</sup>
455
456packToFile (source: PixelMap, fd: number, options: PackingOption,  callback: AsyncCallback\<void>): void
457
458指定编码参数,将PixelMap直接编码进文件。使用callback形式返回结果。
459
460> **注意:**
461> 接口如果返回62980115错误码,表明参数异常,可能是PixelMap对象被提前释放了。需要调用方排查,在该方法调用结束后再释放PixelMap对象。
462
463**系统能力:** SystemCapability.Multimedia.Image.ImagePacker
464
465**参数:**
466
467| 参数名   | 类型                            | 必填 | 说明                           |
468| -------- | ------------------------------- | ---- | ------------------------------ |
469| source   | [PixelMap](arkts-apis-image-PixelMap.md)          | 是   | 编码的PixelMap资源。           |
470| fd       | number                          | 是   | 文件描述符。                   |
471| options   | [PackingOption](arkts-apis-image-i.md#packingoption) | 是   | 设置编码参数。                 |
472| callback | AsyncCallback\<void>            | 是   | 回调函数,当编码图片进文件成功,err为undefined,否则为错误对象。  |
473
474**错误码:**
475
476以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
477
478| 错误码ID | 错误信息 |
479| ------- | --------------------------------------------|
480| 62980096| The operation failed. Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.              |
481| 62980101 | The image data is abnormal. |
482| 62980106 | The image data is too large. This status code is thrown when an error occurs during the process of checking size. |
483| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted.            |
484| 62980115 | Invalid input parameter. |
485| 62980119 | Failed to encode the image. |
486| 62980120 | Add pixelmap out of range. |
487| 62980172 | Failed to encode icc. |
488| 62980252 | Failed to create surface. |
489
490**示例:**
491
492```ts
493import { BusinessError } from '@kit.BasicServicesKit';
494import { fileIo as fs } from '@kit.CoreFileKit';
495
496async function PackToFile(context : Context) {
497  const color: ArrayBuffer = new ArrayBuffer(96); // 96为需要创建的像素buffer大小,取值为:height * width *4。
498  let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
499  const path: string = context.filesDir + "/pixel_map.jpg";
500  image.createPixelMap(color, opts).then((pixelmap: image.PixelMap) => {
501    let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }
502    let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
503    const imagePackerObj: image.ImagePacker = image.createImagePacker();
504    imagePackerObj.packToFile(pixelmap, file.fd, packOpts, (err: BusinessError) => {
505      if (err) {
506        console.error(`Failed to pack the image to file.code ${err.code},message is ${err.message}`);
507      } else {
508        console.info('Succeeded in packing the image to file.');
509      }
510    })
511  })
512}
513```
514
515## packToFile<sup>11+</sup>
516
517packToFile (source: PixelMap, fd: number, options: PackingOption): Promise\<void>
518
519指定编码参数,将PixelMap直接编码进文件。使用Promise形式返回结果。
520
521> **注意:**
522> 接口如果返回62980115错误码,表明参数异常,可能是PixelMap对象被提前释放了。需要调用方排查,在该方法调用结束后再释放PixelMap对象。
523
524**系统能力:** SystemCapability.Multimedia.Image.ImagePacker
525
526**参数:**
527
528| 参数名 | 类型                            | 必填 | 说明                 |
529| ------ | ------------------------------- | ---- | -------------------- |
530| source | [PixelMap](arkts-apis-image-PixelMap.md)          | 是   | 编码的PixelMap资源。 |
531| fd     | number                          | 是   | 文件描述符。         |
532| options | [PackingOption](arkts-apis-image-i.md#packingoption) | 是   | 设置编码参数。       |
533
534**返回值:**
535
536| 类型           | 说明                              |
537| -------------- | --------------------------------- |
538| Promise\<void> |  Promise对象。无返回结果的Promise对象。|
539
540**错误码:**
541
542以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
543
544| 错误码ID | 错误信息 |
545| ------- | --------------------------------------------|
546| 62980096| The operation failed. Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory.              |
547| 62980101 | The image data is abnormal. |
548| 62980106 | The image data is too large. This status code is thrown when an error occurs during the process of checking size. |
549| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted.            |
550| 62980115 | Invalid input parameter. |
551| 62980119 | Failed to encode the image. |
552| 62980120 | Add pixelmap out of range. |
553| 62980172 | Failed to encode icc. |
554| 62980252 | Failed to create surface. |
555
556**示例:**
557
558```ts
559import { BusinessError } from '@kit.BasicServicesKit';
560import { fileIo as fs } from '@kit.CoreFileKit';
561
562async function PackToFile(context : Context) {
563  const color: ArrayBuffer = new ArrayBuffer(96); // 96为需要创建的像素buffer大小,取值为:height * width *4。
564  let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
565  const path: string = context.filesDir + "/pixel_map.jpg";
566  image.createPixelMap(color, opts).then((pixelmap: image.PixelMap) => {
567    let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }
568    let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
569    const imagePackerObj: image.ImagePacker = image.createImagePacker();
570    imagePackerObj.packToFile(pixelmap, file.fd, packOpts)
571      .then(() => {
572        console.info('Succeeded in packing the image to file.');
573      }).catch((error: BusinessError) => {
574      console.error(`Failed to pack the image to file.code ${error.code},message is ${error.message}`);
575    })
576  })
577}
578```
579
580## packToFile<sup>13+</sup>
581
582packToFile(picture: Picture, fd: number, options: PackingOption): Promise\<void>
583
584指定编码参数,将Picture直接编码进文件。使用Promise形式返回结果。
585
586**系统能力:** SystemCapability.Multimedia.Image.ImagePacker
587
588**参数:**
589
590| 参数名  | 类型                         | 必填 | 说明                 |
591| ------- | ---------------------------- | ---- | -------------------- |
592| picture  | [Picture](arkts-apis-image-Picture.md)          | 是   | 编码的Picture资源。 |
593| fd      | number                       | 是   | 文件描述符。         |
594| options | [PackingOption](arkts-apis-image-i.md#packingoption) | 是   | 设置编码参数。       |
595
596**返回值:**
597
598| 类型           | 说明                      |
599| -------------- | ------------------------- |
600| Promise\<void> | 无返回结果的Promise对象。 |
601
602**错误码:**
603
604以下错误码的详细介绍请参见[Image错误码](errorcode-image.md)。
605
606| 错误码ID | 错误信息                                                     |
607| -------- | ------------------------------------------------------------ |
608| 401      | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
609| 7800301  | Encode failed.                                         |
610
611**示例:**
612
613```ts
614import { BusinessError } from '@kit.BasicServicesKit';
615import { fileIo as fs } from '@kit.CoreFileKit';
616
617async function PackToFile(context: Context) {
618  const resourceMgr = context.resourceManager;
619  const rawFile = await resourceMgr.getRawFileContent("test.jpg");
620  let ops: image.SourceOptions = {
621    sourceDensity: 98,
622  }
623  let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
624  let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap();
625  let pictureObj: image.Picture = image.createPicture(commodityPixelMap);
626
627  let funcName = "PackToFile";
628  const imagePackerObj: image.ImagePacker = image.createImagePacker();
629  if (imagePackerObj != null) {
630    const filePath: string = context.filesDir + "/test.jpg";
631    let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
632    let packOpts: image.PackingOption = {
633      format: "image/jpeg",
634      quality: 98,
635      bufferSize: 10,
636      desiredDynamicRange: image.PackingDynamicRange.AUTO,
637      needsPackProperties: true};
638    await imagePackerObj.packToFile(pictureObj, file.fd, packOpts).then(() => {
639      console.info(funcName, 'Succeeded in packing the image to file.');
640    }).catch((error: BusinessError) => {
641      console.error(funcName, `Failed to pack the image to file.code ${error.code},message is ${error.message}`);
642    });
643  }
644}
645```
646
647## packToFileFromPixelmapSequence<sup>18+</sup>
648
649packToFileFromPixelmapSequence(pixelmapSequence: Array\<PixelMap>, fd: number, options: PackingOptionsForSequence): Promise\<void>
650
651指定编码参数,将多个PixelMap编码成GIF文件。使用Promise形式返回结果。
652
653**系统能力:** SystemCapability.Multimedia.Image.ImagePacker
654
655**参数:**
656
657| 参数名           | 类型                                                      | 必填 | 说明                   |
658| ---------------- | --------------------------------------------------------- | ---- | ---------------------- |
659| pixelmapSequence | Array<[PixelMap](arkts-apis-image-PixelMap.md)>                             | 是   | 待编码的PixelMap序列。 |
660| fd               | number                                                    | 是   | 文件描述符。           |
661| options          | [PackingOptionsForSequence](arkts-apis-image-i.md#packingoptionsforsequence18) | 是   | 动图编码参数。         |
662
663**返回值:**
664
665| 类型           | 说明                      |
666| -------------- | ------------------------- |
667| Promise\<void> | 无返回结果的Promise对象。 |
668
669**错误码:**
670
671以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[Image错误码](errorcode-image.md)。
672
673| 错误码ID | 错误信息                                                     |
674| -------- | ------------------------------------------------------------ |
675| 401      | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
676| 7800301  | Failed to encode image.                                      |
677
678**示例:**
679
680```ts
681import { BusinessError } from '@kit.BasicServicesKit';
682import { fileIo as fs } from '@kit.CoreFileKit';
683
684async function PackToFile(context : Context) {
685  const resourceMgr = context.resourceManager;
686  // 此处'moving_test.gif'仅作示例,请开发者自行替换。否则imageSource会创建失败,导致后续无法正常执行。
687  const fileData = await resourceMgr.getRawFileContent('moving_test.gif');
688  const color = fileData.buffer;
689  let imageSource = image.createImageSource(color);
690  let pixelMapList = await imageSource.createPixelMapList();
691  let path: string = context.cacheDir + '/result.gif';
692  let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
693  let ops: image.PackingOptionsForSequence = {
694    frameCount: 3,  // 指定GIF编码中的帧数为3。
695    delayTimeList: [10, 10, 10],  // 指定GIF编码中3帧的延迟时间分别为100ms、100ms、100ms。
696    disposalTypes: [3, 2, 3], // 指定GIF编码中3帧的帧过渡模式分别为3(恢复到之前的状态)、2(恢复背景色)、3(恢复到之前的状态)。
697    loopCount: 0 // 指定GIF编码中循环次数为无限循环。
698  };
699  let Packer = image.createImagePacker();
700  Packer.packToFileFromPixelmapSequence(pixelMapList, file.fd, ops)
701    .then(() => {
702      console.info('Succeeded in packToFileMultiFrames.');
703    }).catch((error: BusinessError) => {
704    console.error('Failed to packToFileMultiFrames.');
705  })
706}
707```
708
709## packing<sup>(deprecated)</sup>
710
711packing(source: ImageSource, option: PackingOption, callback: AsyncCallback\<ArrayBuffer>): void
712
713图片压缩或重新编码,使用callback形式返回结果。
714
715> **说明:**
716>
717> 从API version 6开始支持,从API version 13开始废弃,建议使用[packToData](#packtodata13)代替。
718
719**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
720
721**系统能力:** SystemCapability.Multimedia.Image.ImagePacker
722
723**参数:**
724
725| 参数名   | 类型                               | 必填 | 说明                               |
726| -------- | ---------------------------------- | ---- | ---------------------------------- |
727| source   | [ImageSource](arkts-apis-image-ImageSource.md)        | 是   | 编码的ImageSource。                     |
728| option   | [PackingOption](arkts-apis-image-i.md#packingoption)    | 是   | 设置编码参数。                      |
729| callback | AsyncCallback\<ArrayBuffer>        | 是   | 回调函数,当图片编码成功,err为undefined,data为获取到的压缩或编码数据;否则为错误对象。  |
730
731**示例:**
732
733```ts
734import { BusinessError } from '@kit.BasicServicesKit';
735
736async function Packing(context : Context) {
737  // 此处'test.jpg'仅作示例,请开发者自行替换,否则imageSource会创建失败导致后续无法正常执行。
738  let filePath: string = context.filesDir + "/test.jpg";
739  const imageSourceObj: image.ImageSource = image.createImageSource(filePath);
740  let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 };
741  const imagePackerObj: image.ImagePacker = image.createImagePacker();
742  imagePackerObj.packing(imageSourceObj, packOpts, (err: BusinessError, data: ArrayBuffer) => {
743    if (err) {
744      console.error(`Failed to pack the image.code ${err.code},message is ${err.message}`);
745    } else {
746      console.info('Succeeded in packing the image.');
747    }
748  })
749}
750```
751
752## packing<sup>(deprecated)</sup>
753
754packing(source: ImageSource, option: PackingOption): Promise\<ArrayBuffer>
755
756图片压缩或重新编码,使用Promise形式返回结果。
757
758> **说明:**
759>
760> 从API version 6开始支持,从API version 13开始废弃,建议使用[packToData](#packtodata13)代替。
761
762**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
763
764**系统能力:** SystemCapability.Multimedia.Image.ImagePacker
765
766**参数:**
767
768| 参数名 | 类型                            | 必填 | 说明           |
769| ------ | ------------------------------- | ---- | -------------- |
770| source | [ImageSource](arkts-apis-image-ImageSource.md)     | 是   | 编码的ImageSource。 |
771| option | [PackingOption](arkts-apis-image-i.md#packingoption) | 是   | 设置编码参数。 |
772
773**返回值:**
774
775| 类型                         | 说明                                          |
776| ---------------------------- | --------------------------------------------- |
777| Promise\<ArrayBuffer>        | Promise对象,返回压缩或编码后的数据。 |
778
779**示例:**
780
781```ts
782import { BusinessError } from '@kit.BasicServicesKit';
783
784async function Packing(context : Context) {
785  // 此处'test.jpg'仅作示例,请开发者自行替换,否则imageSource会创建失败导致后续无法正常执行。
786  let filePath: string = context.filesDir + "/test.jpg";
787  const imageSourceObj: image.ImageSource = image.createImageSource(filePath);
788  let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }
789  const imagePackerObj: image.ImagePacker = image.createImagePacker();
790  imagePackerObj.packing(imageSourceObj, packOpts)
791    .then((data: ArrayBuffer) => {
792      console.info('Succeeded in packing the image.');
793    }).catch((error: BusinessError) => {
794      console.error(`Failed to pack the image.code ${error.code},message is ${error.message}`);
795    })
796}
797```
798
799## packing<sup>(deprecated)</sup>
800
801packing(source: PixelMap, option: PackingOption, callback: AsyncCallback\<ArrayBuffer>): void
802
803图片压缩或重新编码,使用callback形式返回结果。
804
805> **说明:**
806>
807> 从API version 8开始支持,从API version 13开始废弃,建议使用[packToData](#packtodata13)代替。
808
809> **注意:**
810> 接口如果返回"PixelMap mismatch",表明参数异常,可能是PixelMap对象被提前释放了。需要调用方排查,在该方法调用结束后再释放PixelMap对象。
811
812**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
813
814**系统能力:** SystemCapability.Multimedia.Image.ImagePacker
815
816**参数:**
817
818| 参数名   | 类型                            | 必填 | 说明                               |
819| -------- | ------------------------------- | ---- | ---------------------------------- |
820| source   | [PixelMap](arkts-apis-image-PixelMap.md)           | 是   | 编码的PixelMap资源。               |
821| option   | [PackingOption](arkts-apis-image-i.md#packingoption) | 是   | 设置编码参数。                     |
822| callback | AsyncCallback\<ArrayBuffer>     | 是   | 回调函数,当图片编码成功,err为undefined,data为获取到的压缩或编码数据;否则为错误对象。  |
823
824**示例:**
825
826```ts
827import { BusinessError } from '@kit.BasicServicesKit';
828
829async function Packing() {
830  const color: ArrayBuffer = new ArrayBuffer(96); // 96为需要创建的像素buffer大小,取值为:height * width *4。
831  let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
832  image.createPixelMap(color, opts).then((pixelMap: image.PixelMap) => {
833    let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }
834    const imagePackerObj: image.ImagePacker = image.createImagePacker();
835    imagePackerObj.packing(pixelMap, packOpts, (err: BusinessError, data: ArrayBuffer) => {
836      if (err) {
837        console.error(`Failed to pack the image.code ${err.code},message is ${err.message}`);
838      } else {
839        console.info('Succeeded in packing the image.');
840      }
841    })
842  }).catch((error: BusinessError) => {
843    console.error(`Failed to create the PixelMap.code ${error.code},message is ${error.message}`);
844  })
845}
846```
847
848## packing<sup>(deprecated)</sup>
849
850packing(source: PixelMap, option: PackingOption): Promise\<ArrayBuffer>
851
852图片压缩或重新编码,使用Promise形式返回结果。
853
854> **说明:**
855>
856> 从API version 8开始支持,从API version 13开始废弃,建议使用[packToData](#packtodata13)代替。
857
858> **注意:**
859> 接口如果返回"PixelMap mismatch",表明参数异常,可能是PixelMap对象被提前释放了。需要调用方排查,在该方法调用结束后再释放PixelMap对象。
860
861**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
862
863**系统能力:** SystemCapability.Multimedia.Image.ImagePacker
864
865**参数:**
866
867| 参数名 | 类型                            | 必填 | 说明               |
868| ------ | ------------------------------- | ---- | ------------------ |
869| source | [PixelMap](arkts-apis-image-PixelMap.md)           | 是   | 编码的PixelMap源。 |
870| option | [PackingOption](arkts-apis-image-i.md#packingoption) | 是   | 设置编码参数。     |
871
872**返回值:**
873
874| 类型                  | 说明                                         |
875| --------------------- | -------------------------------------------- |
876| Promise\<ArrayBuffer> | Promise对象,返回压缩或编码后的数据。|
877
878**示例:**
879
880```ts
881import { BusinessError } from '@kit.BasicServicesKit';
882
883async function Packing() {
884  const color: ArrayBuffer = new ArrayBuffer(96); // 96为需要创建的像素buffer大小,取值为:height * width *4。
885  let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
886  image.createPixelMap(color, opts).then((pixelMap: image.PixelMap) => {
887    let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }
888    const imagePackerObj: image.ImagePacker = image.createImagePacker();
889    imagePackerObj.packing(pixelMap, packOpts)
890      .then((data: ArrayBuffer) => {
891        console.info('Succeeded in packing the image.');
892      }).catch((error: BusinessError) => {
893      console.error(`Failed to pack the image.code ${error.code},message is ${error.message}`);
894    })
895  }).catch((error: BusinessError) => {
896    console.error(`Failed to create PixelMap.code ${error.code},message is ${error.message}`);
897  })
898}
899```
900