1# Interface (ImagePacker) 2<!--Kit: Image Kit--> 3<!--Subsystem: Multimedia--> 4<!--Owner: @aulight02--> 5<!--SE: @liyang_bryan--> 6<!--TSE: @xchaosioda--> 7 8> **NOTE** 9> 10> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. 11 12The **ImagePacker** class provides APIs to compress and encode images. Before calling any API in ImagePacker, you must use [createImagePacker](arkts-apis-image-f.md#imagecreateimagepacker) to create an ImagePacker object. Currently, this class applies only to images in .jpeg, .webp, .png, or heif<sup>12+</sup> (depending on the hardware). 13 14## Modules to Import 15 16```ts 17import { image } from '@kit.ImageKit'; 18``` 19 20## Properties 21 22**System capability**: SystemCapability.Multimedia.Image.ImagePacker 23 24| Name | Type | Read Only| Optional| Description | 25| ---------------- | -------------- | ---- | ---- | -------------------------- | 26| supportedFormats | Array\<string> | Yes | No | Supported formats, including .jpeg, .webp, .png, and heic<sup>12+</sup> (depending on the hardware).| 27 28## packToData<sup>13+</sup> 29 30packToData(source: ImageSource, options: PackingOption): Promise\<ArrayBuffer> 31 32Compresses or re-encodes an image. This API uses a promise to return the result. 33 34**Atomic service API**: This API can be used in atomic services since API version 13. 35 36**System capability**: SystemCapability.Multimedia.Image.ImagePacker 37 38**Parameters** 39 40| Name| Type | Mandatory| Description | 41| ------ | ------------------------------- | ---- | -------------- | 42| source | [ImageSource](arkts-apis-image-ImageSource.md) | Yes | Image source to compress or re-encode.| 43| options | [PackingOption](arkts-apis-image-i.md#packingoption) | Yes | Encoding parameters.| 44 45**Error codes** 46 47For details about the error codes, see [Image Error Codes](errorcode-image.md). 48 49| ID| Error Message| 50| ------- | --------------------------------------------| 51| 401 | If the parameter is invalid. | 52| 62980096| The operation failed. Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory. | 53| 62980101 | The image data is abnormal. | 54| 62980106 | The image data is too large. This status code is thrown when an error occurs during the process of checking size. | 55| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted. | 56| 62980119 | Failed to encode the image. | 57| 62980120 | Add pixelmap out of range. | 58| 62980172 | Failed to encode icc. | 59| 62980252 | Failed to create surface. | 60 61**Return value** 62 63| Type | Description | 64| ---------------------------- | --------------------------------------------- | 65| Promise\<ArrayBuffer> | Promise used to return the compressed or encoded image data.| 66 67**Example** 68 69<!--code_no_check--> 70```ts 71import { common } from '@kit.AbilityKit'; 72import { BusinessError } from '@kit.BasicServicesKit'; 73 74// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 75let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 76// 'test.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed. 77let filePath: string = context.filesDir + "/test.jpg"; 78const imageSourceApi: image.ImageSource = image.createImageSource(filePath); 79let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 } 80const imagePackerApi: image.ImagePacker = image.createImagePacker(); 81imagePackerApi.packToData(imageSourceApi, packOpts) 82 .then((data: ArrayBuffer) => { 83 console.info('Succeeded in packing the image.'); 84 }).catch((error: BusinessError) => { 85 console.error(`Failed to pack the image.code ${error.code},message is ${error.message}`); 86 }) 87``` 88 89## packToData<sup>13+</sup> 90 91packToData(source: PixelMap, options: PackingOption): Promise\<ArrayBuffer> 92 93Compresses or re-encodes an image. This API uses a promise to return the result. 94 95> **NOTE** 96> 97> If error code 401 is returned, the parameters are abnormal. The possible cause is that the PixelMap object is released in advance. You need to check the code and ensure that the PixelMap object is released after this API is called. 98 99**Atomic service API**: This API can be used in atomic services since API version 13. 100 101**System capability**: SystemCapability.Multimedia.Image.ImagePacker 102 103**Parameters** 104 105| Name| Type | Mandatory| Description | 106| ------ | ------------------------------- | ---- | ------------------ | 107| source | [PixelMap](arkts-apis-image-PixelMap.md) | Yes | PixelMap to compress or re-encode.| 108| options | [PackingOption](arkts-apis-image-i.md#packingoption) | Yes | Encoding parameters. | 109 110**Return value** 111 112| Type | Description | 113| --------------------- | -------------------------------------------- | 114| Promise\<ArrayBuffer> | Promise used to return the compressed or encoded image data.| 115 116**Error codes** 117 118For details about the error codes, see [Image Error Codes](errorcode-image.md). 119 120| ID| Error Message| 121| ------- | --------------------------------------------| 122| 401 | If the parameter is invalid. | 123| 62980096| The operation failed. Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory. | 124| 62980101 | The image data is abnormal. | 125| 62980106 | The image data is too large. This status code is thrown when an error occurs during the process of checking size. | 126| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted. | 127| 62980119 | Failed to encode the image. | 128| 62980120 | Add pixelmap out of range. | 129| 62980172 | Failed to encode icc. | 130| 62980252 | Failed to create surface. | 131 132**Example** 133 134```ts 135import { BusinessError } from '@kit.BasicServicesKit'; 136 137const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4. 138let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } 139image.createPixelMap(color, opts).then((pixelMap: image.PixelMap) => { 140 let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 } 141 const imagePackerApi: image.ImagePacker = image.createImagePacker(); 142 imagePackerApi.packToData(pixelMap, packOpts) 143 .then((data: ArrayBuffer) => { 144 console.info('Succeeded in packing the image.'); 145 }).catch((error: BusinessError) => { 146 console.error(`Failed to pack the image.code ${error.code},message is ${error.message}`); 147 }) 148}).catch((error: BusinessError) => { 149 console.error(`Failed to create PixelMap.code ${error.code},message is ${error.message}`); 150}) 151``` 152 153## packing<sup>13+</sup> 154 155packing(picture: Picture, options: PackingOption): Promise\<ArrayBuffer> 156 157Compresses or re-encodes an image. This API uses a promise to return the result. 158 159**System capability**: SystemCapability.Multimedia.Image.ImagePacker 160 161**Parameters** 162 163| Name | Type | Mandatory| Description | 164| ---------------- | ---------------------------------------------------- | ---- | -------------------- | 165| picture | [Picture](arkts-apis-image-Picture.md) | Yes | Picture to compress or re-encode.| 166| options | [PackingOption](arkts-apis-image-i.md#packingoption) | Yes | Encoding parameters. | 167 168**Return value** 169 170| Type | Description | 171| --------------------- | ------------------------------------- | 172| Promise\<ArrayBuffer> | Promise used to return the compressed or encoded image data.| 173 174**Error codes** 175 176For details about the error codes, see [Image Error Codes](errorcode-image.md). 177 178| ID| Error Message | 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**Example** 184 185```ts 186import { BusinessError } from '@kit.BasicServicesKit'; 187import { image } from '@kit.ImageKit'; 188 189async function Packing(context: Context) { 190 const resourceMgr = context.resourceManager; 191 const rawFile = await resourceMgr.getRawFileContent("test.jpg"); 192 let ops: image.SourceOptions = { 193 sourceDensity: 98, 194 } 195 let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops); 196 let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap(); 197 let pictureObj: image.Picture = image.createPicture(commodityPixelMap); 198 const imagePackerApi: image.ImagePacker = image.createImagePacker(); 199 let funcName = "Packing"; 200 if (imagePackerApi != null) { 201 let opts: image.PackingOption = { 202 format: "image/jpeg", 203 quality: 98, 204 bufferSize: 10, 205 desiredDynamicRange: image.PackingDynamicRange.AUTO, 206 needsPackProperties: true}; 207 await imagePackerApi.packing(pictureObj, opts).then((data: ArrayBuffer) => { 208 console.info(funcName, 'Succeeded in packing the image.'+ data); 209 }).catch((error: BusinessError) => { 210 console.error(funcName, 'Failed to pack the image.code ${error.code},message is ${error.message}'); 211 }); 212 } 213} 214``` 215 216## packToDataFromPixelmapSequence<sup>18+</sup> 217 218packToDataFromPixelmapSequence(pixelmapSequence: Array\<PixelMap>, options: PackingOptionsForSequence): Promise\<ArrayBuffer> 219 220Encodes multiple PixelMap objects into GIF data. This API uses a promise to return the result. 221 222**System capability**: SystemCapability.Multimedia.Image.ImagePacker 223 224**Parameters** 225 226| Name | Type | Mandatory| Description | 227| ---------------- | --------------------------------------------------------- | ---- | ---------------------- | 228| pixelmapSequence | Array\<[PixelMap](arkts-apis-image-PixelMap.md)> | Yes | PixelMaps to encode.| 229| options | [PackingOptionsForSequence](arkts-apis-image-i.md#packingoptionsforsequence18) | Yes | Options for encoding animated images. | 230 231**Return value** 232 233| Type | Description | 234| --------------------- | ------------------------------- | 235| Promise\<ArrayBuffer> | Promise used to return the encoded data.| 236 237**Error codes** 238 239For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Image Error Codes](errorcode-image.md). 240 241| ID| Error Message | 242| -------- | ------------------------------------------------------------ | 243| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. | 244| 7800301 | Failed to encode image. | 245 246**Example** 247 248<!--code_no_check--> 249```ts 250import { common } from '@kit.AbilityKit'; 251import { BusinessError } from '@ohos.base'; 252import image from "@ohos.multimedia.image"; 253 254// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 255let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 256const resourceMgr = context.resourceManager; 257// 'moving_test.gif' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed. 258const fileData = resourceMgr.getRawFileContent('moving_test.gif'); 259const color = fileData.buffer; 260let imageSource = image.createImageSource(color); 261let pixelMapList = imageSource.createPixelMapList(); 262let ops: image.PackingOptionsForSequence = { 263 frameCount: 3, // Set the number of frames in GIF encoding to 3. 264 delayTimeList: [10, 10, 10], // Set the delay time of three frames in GIF encoding to 100 ms, 100 ms, and 100 ms, respectively. 265 disposalTypes: [3, 2, 3], // Specify the frame transition modes of the three frames in GIF encoding as 3 (restore to the previous state), 2 (restore to the background color), and 3 (restore to the previous state). 266 loopCount: 0 // Set the number of loops in GIF encoding to infinite. 267}; 268let Packer = image.createImagePacker(); 269Packer.packToDataFromPixelmapSequence(pixelMapList, ops) 270 .then((data: ArrayBuffer) => { 271 console.info('Succeeded in packing.'); 272 }).catch((error: BusinessError) => { 273 console.error('Failed to packing.'); 274 }) 275``` 276 277## release 278 279release(callback: AsyncCallback\<void>): void 280 281Releases this ImagePacker instance. This API uses an asynchronous callback to return the result. 282 283ArkTS supports memory reclamation. Even if the application does not call **release()**, the memory of the ImagePacker object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required. 284 285**System capability**: SystemCapability.Multimedia.Image.ImagePacker 286 287**Parameters** 288 289| Name | Type | Mandatory| Description | 290| -------- | -------------------- | ---- | ------------------------------ | 291| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 292 293**Example** 294 295```ts 296import { BusinessError } from '@kit.BasicServicesKit'; 297 298const imagePackerApi: image.ImagePacker = image.createImagePacker(); 299imagePackerApi.release((err: BusinessError)=>{ 300 if (err) { 301 console.error(`Failed to release image packaging.code ${err.code},message is ${err.message}`); 302 } else { 303 console.info('Succeeded in releasing image packaging.'); 304 } 305}) 306``` 307 308## release 309 310release(): Promise\<void> 311 312Releases this ImagePacker instance. This API uses a promise to return the result. 313 314ArkTS supports memory reclamation. Even if the application does not call **release()**, the memory of the ImagePacker object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required. 315 316**System capability**: SystemCapability.Multimedia.Image.ImagePacker 317 318**Return value** 319 320| Type | Description | 321| -------------- | ------------------------------------------------------ | 322| Promise\<void> | Promise that returns no value.| 323 324**Example** 325 326```ts 327import { BusinessError } from '@kit.BasicServicesKit'; 328 329const imagePackerApi: image.ImagePacker = image.createImagePacker(); 330imagePackerApi.release().then(() => { 331 console.info('Succeeded in releasing image packaging.'); 332}).catch((error: BusinessError) => { 333 console.error(`Failed to release image packaging.code ${error.code},message is ${error.message}`); 334}) 335``` 336 337## packToFile<sup>11+</sup> 338 339packToFile(source: ImageSource, fd: number, options: PackingOption, callback: AsyncCallback\<void>): void 340 341Encodes the image source into a file based on the specified encoding parameters. This API uses an asynchronous callback to return the result. 342 343**System capability**: SystemCapability.Multimedia.Image.ImagePacker 344 345**Parameters** 346 347| Name | Type | Mandatory| Description | 348| -------- | ------------------------------- | ---- | ------------------------------ | 349| source | [ImageSource](arkts-apis-image-ImageSource.md) | Yes | Image source to encode. | 350| fd | number | Yes | File descriptor. | 351| options | [PackingOption](arkts-apis-image-i.md#packingoption) | Yes | Encoding parameters. | 352| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. | 353 354**Error codes** 355 356For details about the error codes, see [Image Error Codes](errorcode-image.md). 357 358| ID| Error Message| 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**Example** 371 372<!--code_no_check--> 373```ts 374import { common } from '@kit.AbilityKit'; 375import { BusinessError } from '@kit.BasicServicesKit'; 376import { fileIo as fs } from '@kit.CoreFileKit'; 377 378// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 379let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 380// 'test.png' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed. 381const path: string = context.filesDir + "/test.png"; 382const imageSourceApi: image.ImageSource = image.createImageSource(path); 383let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }; 384const filePath: string = context.filesDir + "/image_source.jpg"; 385let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 386const imagePackerApi: image.ImagePacker = image.createImagePacker(); 387imagePackerApi.packToFile(imageSourceApi, file.fd, packOpts, (err: BusinessError) => { 388 if (err) { 389 console.error(`Failed to pack the image to file.code ${err.code},message is ${err.message}`); 390 } else { 391 console.info('Succeeded in packing the image to file.'); 392 } 393}) 394``` 395 396## packToFile<sup>11+</sup> 397 398packToFile (source: ImageSource, fd: number, options: PackingOption): Promise\<void> 399 400Encodes the image source into a file based on the specified encoding parameters. This API uses a promise to return the result. 401 402**System capability**: SystemCapability.Multimedia.Image.ImagePacker 403 404**Parameters** 405 406| Name| Type | Mandatory| Description | 407| ------ | ------------------------------- | ---- | -------------- | 408| source | [ImageSource](arkts-apis-image-ImageSource.md) | Yes | Image source to encode.| 409| fd | number | Yes | File descriptor. | 410| options | [PackingOption](arkts-apis-image-i.md#packingoption) | Yes | Encoding parameters.| 411 412**Return value** 413 414| Type | Description | 415| -------------- | --------------------------------- | 416| Promise\<void> | Promise that returns no value.| 417 418**Error codes** 419 420For details about the error codes, see [Image Error Codes](errorcode-image.md). 421 422| ID| Error Message| 423| ------- | --------------------------------------------| 424| 62980096| The operation failed. Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory. | 425| 62980101 | The image data is abnormal. | 426| 62980106 | The image data is too large. This status code is thrown when an error occurs during the process of checking size. | 427| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted. | 428| 62980115 | Invalid input parameter. | 429| 62980119 | Failed to encode the image. | 430| 62980120 | Add pixelmap out of range. | 431| 62980172 | Failed to encode icc. | 432| 62980252 | Failed to create surface. | 433 434**Example** 435 436<!--code_no_check--> 437```ts 438import { common } from '@kit.AbilityKit'; 439import { BusinessError } from '@kit.BasicServicesKit'; 440import { fileIo as fs } from '@kit.CoreFileKit'; 441 442// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 443let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 444// 'test.png' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed. 445const path: string = context.filesDir + "/test.png"; 446const imageSourceApi: image.ImageSource = image.createImageSource(path); 447let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }; 448const filePath: string = context.filesDir + "/image_source.jpg"; 449let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 450const imagePackerApi: image.ImagePacker = image.createImagePacker(); 451imagePackerApi.packToFile(imageSourceApi, file.fd, packOpts).then(() => { 452 console.info('Succeeded in packing the image to file.'); 453}).catch((error: BusinessError) => { 454 console.error(`Failed to pack the image to file.code ${error.code},message is ${error.message}`); 455}) 456``` 457 458## packToFile<sup>11+</sup> 459 460packToFile (source: PixelMap, fd: number, options: PackingOption, callback: AsyncCallback\<void>): void 461 462Encodes the PixelMap into a file based on the specified encoding parameters. This API uses an asynchronous callback to return the result. 463 464> **NOTE** 465> If error code 62980115 is returned, the parameters are abnormal. The possible cause is that the PixelMap object is released in advance. You need to check the code and ensure that the PixelMap object is released after this API is called. 466 467**System capability**: SystemCapability.Multimedia.Image.ImagePacker 468 469**Parameters** 470 471| Name | Type | Mandatory| Description | 472| -------- | ------------------------------- | ---- | ------------------------------ | 473| source | [PixelMap](arkts-apis-image-PixelMap.md) | Yes | PixelMap to encode. | 474| fd | number | Yes | File descriptor. | 475| options | [PackingOption](arkts-apis-image-i.md#packingoption) | Yes | Encoding parameters. | 476| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. | 477 478**Error codes** 479 480For details about the error codes, see [Image Error Codes](errorcode-image.md). 481 482| ID| Error Message| 483| ------- | --------------------------------------------| 484| 62980096| The operation failed. Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory. | 485| 62980101 | The image data is abnormal. | 486| 62980106 | The image data is too large. This status code is thrown when an error occurs during the process of checking size. | 487| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted. | 488| 62980115 | Invalid input parameter. | 489| 62980119 | Failed to encode the image. | 490| 62980120 | Add pixelmap out of range. | 491| 62980172 | Failed to encode icc. | 492| 62980252 | Failed to create surface. | 493 494**Example** 495 496<!--code_no_check--> 497```ts 498import { common } from '@kit.AbilityKit'; 499import { BusinessError } from '@kit.BasicServicesKit'; 500import { fileIo as fs } from '@kit.CoreFileKit'; 501 502const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4. 503let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } } 504// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 505let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 506const path: string = context.filesDir + "/pixel_map.jpg"; 507image.createPixelMap(color, opts).then((pixelmap: image.PixelMap) => { 508 let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 } 509 let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 510 const imagePackerApi: image.ImagePacker = image.createImagePacker(); 511 imagePackerApi.packToFile(pixelmap, file.fd, packOpts, (err: BusinessError) => { 512 if (err) { 513 console.error(`Failed to pack the image to file.code ${err.code},message is ${err.message}`); 514 } else { 515 console.info('Succeeded in packing the image to file.'); 516 } 517 }) 518}) 519``` 520 521## packToFile<sup>11+</sup> 522 523packToFile (source: PixelMap, fd: number, options: PackingOption): Promise\<void> 524 525Encodes the PixelMap into a file based on the specified encoding parameters. This API uses a promise to return the result. 526 527> **NOTE** 528> If error code 62980115 is returned, the parameters are abnormal. The possible cause is that the PixelMap object is released in advance. You need to check the code and ensure that the PixelMap object is released after this API is called. 529 530**System capability**: SystemCapability.Multimedia.Image.ImagePacker 531 532**Parameters** 533 534| Name| Type | Mandatory| Description | 535| ------ | ------------------------------- | ---- | -------------------- | 536| source | [PixelMap](arkts-apis-image-PixelMap.md) | Yes | PixelMap to encode.| 537| fd | number | Yes | File descriptor. | 538| options | [PackingOption](arkts-apis-image-i.md#packingoption) | Yes | Encoding parameters. | 539 540**Return value** 541 542| Type | Description | 543| -------------- | --------------------------------- | 544| Promise\<void> | Promise that returns no value.| 545 546**Error codes** 547 548For details about the error codes, see [Image Error Codes](errorcode-image.md). 549 550| ID| Error Message| 551| ------- | --------------------------------------------| 552| 62980096| The operation failed. Possible cause: 1.Image upload exception. 2. Decoding process exception. 3. Insufficient memory. | 553| 62980101 | The image data is abnormal. | 554| 62980106 | The image data is too large. This status code is thrown when an error occurs during the process of checking size. | 555| 62980113| Unknown image format.The image data provided is not in a recognized or supported format, or it may be occorrupted. | 556| 62980115 | Invalid input parameter. | 557| 62980119 | Failed to encode the image. | 558| 62980120 | Add pixelmap out of range. | 559| 62980172 | Failed to encode icc. | 560| 62980252 | Failed to create surface. | 561 562**Example** 563 564<!--code_no_check--> 565```ts 566import { common } from '@kit.AbilityKit'; 567import { BusinessError } from '@kit.BasicServicesKit'; 568import { fileIo as fs } from '@kit.CoreFileKit'; 569 570const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4. 571let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } } 572// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 573let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 574const path: string = context.filesDir + "/pixel_map.jpg"; 575image.createPixelMap(color, opts).then((pixelmap: image.PixelMap) => { 576 let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 } 577 let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 578 const imagePackerApi: image.ImagePacker = image.createImagePacker(); 579 imagePackerApi.packToFile(pixelmap, file.fd, packOpts) 580 .then(() => { 581 console.info('Succeeded in packing the image to file.'); 582 }).catch((error: BusinessError) => { 583 console.error(`Failed to pack the image to file.code ${error.code},message is ${error.message}`); 584 }) 585}) 586``` 587 588## packToFile<sup>13+</sup> 589 590packToFile(picture: Picture, fd: number, options: PackingOption): Promise\<void> 591 592Encodes the Picture into a file based on the specified encoding parameters. This API uses a promise to return the result. 593 594**System capability**: SystemCapability.Multimedia.Image.ImagePacker 595 596**Parameters** 597 598| Name | Type | Mandatory| Description | 599| ------- | ---------------------------- | ---- | -------------------- | 600| picture | [Picture](arkts-apis-image-Picture.md) | Yes | Picture to encode.| 601| fd | number | Yes | File descriptor. | 602| options | [PackingOption](arkts-apis-image-i.md#packingoption) | Yes | Encoding parameters. | 603 604**Return value** 605 606| Type | Description | 607| -------------- | ------------------------- | 608| Promise\<void> | that returns no value.| 609 610**Error codes** 611 612For details about the error codes, see [Image Error Codes](errorcode-image.md). 613 614| ID| Error Message | 615| -------- | ------------------------------------------------------------ | 616| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. | 617| 7800301 | Encode failed. | 618 619**Example** 620 621```ts 622import { BusinessError } from '@kit.BasicServicesKit'; 623import { image } from '@kit.ImageKit'; 624import { fileIo as fs } from '@kit.CoreFileKit'; 625 626async function PackToFile(context: Context) { 627 const resourceMgr = context.resourceManager; 628 const rawFile = await resourceMgr.getRawFileContent("test.jpg"); 629 let ops: image.SourceOptions = { 630 sourceDensity: 98, 631 } 632 let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops); 633 let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap(); 634 let pictureObj: image.Picture = image.createPicture(commodityPixelMap); 635 636 let funcName = "PackToFile"; 637 const imagePackerApi: image.ImagePacker = image.createImagePacker(); 638 if (imagePackerApi != null) { 639 const filePath: string = context.filesDir + "/test.jpg"; 640 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 641 let packOpts: image.PackingOption = { 642 format: "image/jpeg", 643 quality: 98, 644 bufferSize: 10, 645 desiredDynamicRange: image.PackingDynamicRange.AUTO, 646 needsPackProperties: true}; 647 await imagePackerApi.packToFile(pictureObj, file.fd, packOpts).then(() => { 648 console.info(funcName, 'Succeeded in packing the image to file.'); 649 }).catch((error: BusinessError) => { 650 console.error(funcName, 'Failed to pack the image to file.code ${error.code},message is ${error.message}'); 651 }); 652 } 653} 654``` 655 656## packToFileFromPixelmapSequence<sup>18+</sup> 657 658packToFileFromPixelmapSequence(pixelmapSequence: Array\<PixelMap>, fd: number, options: PackingOptionsForSequence): Promise\<void> 659 660Encodes multiple PixelMaps into a GIF file. This API uses a promise to return the result. 661 662**System capability**: SystemCapability.Multimedia.Image.ImagePacker 663 664**Parameters** 665 666| Name | Type | Mandatory| Description | 667| ---------------- | --------------------------------------------------------- | ---- | ---------------------- | 668| pixelmapSequence | Array<[PixelMap](arkts-apis-image-PixelMap.md)> | Yes | PixelMaps to encode.| 669| fd | number | Yes | File descriptor. | 670| options | [PackingOptionsForSequence](arkts-apis-image-i.md#packingoptionsforsequence18) | Yes | Options for encoding animated images. | 671 672**Return value** 673 674| Type | Description | 675| -------------- | ------------------------- | 676| Promise\<void> | that returns no value.| 677 678**Error codes** 679 680For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Image Error Codes](errorcode-image.md). 681 682| ID| Error Message | 683| -------- | ------------------------------------------------------------ | 684| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. | 685| 7800301 | Failed to encode image. | 686 687**Example** 688 689<!--code_no_check--> 690```ts 691import { common } from '@kit.AbilityKit'; 692import { BusinessError } from '@ohos.base'; 693import fs from '@ohos.file.fs'; 694import image from "@ohos.multimedia.image"; 695 696// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 697let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 698const resourceMgr = context.resourceManager; 699// 'moving_test.gif' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed. 700const fileData = await resourceMgr.getRawFileContent('moving_test.gif'); 701const color = fileData.buffer; 702let imageSource = image.createImageSource(color); 703let pixelMapList = await imageSource.createPixelMapList(); 704let path: string = context.cacheDir + '/result.gif'; 705let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 706let ops: image.PackingOptionsForSequence = { 707 frameCount: 3, // Set the number of frames in GIF encoding to 3. 708 delayTimeList: [10, 10, 10], // Set the delay time of three frames in GIF encoding to 100 ms, 100 ms, and 100 ms, respectively. 709 disposalTypes: [3, 2, 3], // Specify the frame transition modes of the three frames in GIF encoding as 3 (restore to the previous state), 2 (restore to the background color), and 3 (restore to the previous state). 710 loopCount: 0 // Set the number of loops in GIF encoding to infinite. 711}; 712let Packer = image.createImagePacker(); 713Packer.packToFileFromPixelmapSequence(pixelMapList, file.fd, ops) 714 .then(() => { 715 console.info('Succeeded in packToFileMultiFrames.'); 716 }).catch((error: BusinessError) => { 717 console.error('Failed to packToFileMultiFrames.'); 718 }) 719``` 720 721## packing<sup>(deprecated)</sup> 722 723packing(source: ImageSource, option: PackingOption, callback: AsyncCallback\<ArrayBuffer>): void 724 725Compresses or re-encodes an image. This API uses an asynchronous callback to return the result. 726 727> **NOTE** 728> 729> This API is supported since API version 6 and deprecated since API version 13. Use [packToData](#packtodata13) instead. 730 731**Atomic service API**: This API can be used in atomic services since API version 11. 732 733**System capability**: SystemCapability.Multimedia.Image.ImagePacker 734 735**Parameters** 736 737| Name | Type | Mandatory| Description | 738| -------- | ---------------------------------- | ---- | ---------------------------------- | 739| source | [ImageSource](arkts-apis-image-ImageSource.md) | Yes | Image source to compress or re-encode. | 740| option | [PackingOption](arkts-apis-image-i.md#packingoption) | Yes | Encoding parameters. | 741| callback | AsyncCallback\<ArrayBuffer> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the compressed or encoded image data; otherwise, **err** is an error object. | 742 743**Example** 744 745<!--code_no_check--> 746```ts 747import { common } from '@kit.AbilityKit'; 748import { BusinessError } from '@kit.BasicServicesKit'; 749 750// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 751let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 752// 'test.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed. 753let filePath: string = context.filesDir + "/test.jpg"; 754const imageSourceApi: image.ImageSource = image.createImageSource(filePath); 755let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }; 756const imagePackerApi: image.ImagePacker = image.createImagePacker(); 757imagePackerApi.packing(imageSourceApi, packOpts, (err: BusinessError, data: ArrayBuffer) => { 758 if (err) { 759 console.error(`Failed to pack the image.code ${err.code},message is ${err.message}`); 760 } else { 761 console.info('Succeeded in packing the image.'); 762 } 763}) 764``` 765 766## packing<sup>(deprecated)</sup> 767 768packing(source: ImageSource, option: PackingOption): Promise\<ArrayBuffer> 769 770Compresses or re-encodes an image. This API uses a promise to return the result. 771 772> **NOTE** 773> 774> This API is supported since API version 6 and deprecated since API version 13. Use [packToData](#packtodata13) instead. 775 776**Atomic service API**: This API can be used in atomic services since API version 11. 777 778**System capability**: SystemCapability.Multimedia.Image.ImagePacker 779 780**Parameters** 781 782| Name| Type | Mandatory| Description | 783| ------ | ------------------------------- | ---- | -------------- | 784| source | [ImageSource](arkts-apis-image-ImageSource.md) | Yes | Image source to compress or re-encode.| 785| option | [PackingOption](arkts-apis-image-i.md#packingoption) | Yes | Encoding parameters.| 786 787**Return value** 788 789| Type | Description | 790| ---------------------------- | --------------------------------------------- | 791| Promise\<ArrayBuffer> | Promise used to return the compressed or encoded image data.| 792 793**Example** 794 795<!--code_no_check--> 796```ts 797import { common } from '@kit.AbilityKit'; 798import { BusinessError } from '@kit.BasicServicesKit'; 799 800// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 801let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 802// 'test.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed. 803let filePath: string = context.filesDir + "/test.jpg"; 804const imageSourceApi: image.ImageSource = image.createImageSource(filePath); 805let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 } 806const imagePackerApi: image.ImagePacker = image.createImagePacker(); 807imagePackerApi.packing(imageSourceApi, packOpts) 808 .then((data: ArrayBuffer) => { 809 console.info('Succeeded in packing the image.'); 810 }).catch((error: BusinessError) => { 811 console.error(`Failed to pack the image.code ${error.code},message is ${error.message}`); 812 }) 813``` 814 815## packing<sup>(deprecated)</sup> 816 817packing(source: PixelMap, option: PackingOption, callback: AsyncCallback\<ArrayBuffer>): void 818 819Compresses or re-encodes an image. This API uses an asynchronous callback to return the result. 820 821> **NOTE** 822> 823> This API is supported since API version 8 and deprecated since API version 13. Use [packToData](#packtodata13) instead. 824 825> **NOTE** 826> If the message "PixelMap mismatch" is returned, the parameters are abnormal. The possible cause is that the PixelMap object is released in advance. You need to check the code and ensure that the PixelMap object is released after this API is called. 827 828**Atomic service API**: This API can be used in atomic services since API version 11. 829 830**System capability**: SystemCapability.Multimedia.Image.ImagePacker 831 832**Parameters** 833 834| Name | Type | Mandatory| Description | 835| -------- | ------------------------------- | ---- | ---------------------------------- | 836| source | [PixelMap](arkts-apis-image-PixelMap.md) | Yes | PixelMap to compress or re-encode. | 837| option | [PackingOption](arkts-apis-image-i.md#packingoption) | Yes | Encoding parameters. | 838| callback | AsyncCallback\<ArrayBuffer> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the compressed or encoded image data; otherwise, **err** is an error object. | 839 840**Example** 841 842```ts 843import { BusinessError } from '@kit.BasicServicesKit'; 844 845const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4. 846let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } } 847image.createPixelMap(color, opts).then((pixelMap: image.PixelMap) => { 848 let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 } 849 const imagePackerApi: image.ImagePacker = image.createImagePacker(); 850 imagePackerApi.packing(pixelMap, packOpts, (err: BusinessError, data: ArrayBuffer) => { 851 if (err) { 852 console.error(`Failed to pack the image.code ${err.code},message is ${err.message}`); 853 } else { 854 console.info('Succeeded in packing the image.'); 855 } 856 }) 857}).catch((error: BusinessError) => { 858 console.error(`Failed to create the PixelMap.code ${error.code},message is ${error.message}`); 859}) 860``` 861 862## packing<sup>(deprecated)</sup> 863 864packing(source: PixelMap, option: PackingOption): Promise\<ArrayBuffer> 865 866Compresses or re-encodes an image. This API uses a promise to return the result. 867 868> **NOTE** 869> 870> This API is supported since API version 8 and deprecated since API version 13. Use [packToData](#packtodata13) instead. 871> 872> If the message "PixelMap mismatch" is returned, the parameters are abnormal. The possible cause is that the PixelMap object is released in advance. You need to check the code and ensure that the PixelMap object is released after this API is called. 873 874**Atomic service API**: This API can be used in atomic services since API version 11. 875 876**System capability**: SystemCapability.Multimedia.Image.ImagePacker 877 878**Parameters** 879 880| Name| Type | Mandatory| Description | 881| ------ | ------------------------------- | ---- | ------------------ | 882| source | [PixelMap](arkts-apis-image-PixelMap.md) | Yes | PixelMap to compress or re-encode.| 883| option | [PackingOption](arkts-apis-image-i.md#packingoption) | Yes | Encoding parameters. | 884 885**Return value** 886 887| Type | Description | 888| --------------------- | -------------------------------------------- | 889| Promise\<ArrayBuffer> | Promise used to return the compressed or encoded image data.| 890 891**Example** 892 893```ts 894import { BusinessError } from '@kit.BasicServicesKit'; 895 896const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4. 897let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } } 898image.createPixelMap(color, opts).then((pixelMap: image.PixelMap) => { 899 let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 } 900 const imagePackerApi: image.ImagePacker = image.createImagePacker(); 901 imagePackerApi.packing(pixelMap, packOpts) 902 .then((data: ArrayBuffer) => { 903 console.info('Succeeded in packing the image.'); 904 }).catch((error: BusinessError) => { 905 console.error(`Failed to pack the image.code ${error.code},message is ${error.message}`); 906 }) 907}).catch((error: BusinessError) => { 908 console.error(`Failed to create PixelMap.code ${error.code},message is ${error.message}`); 909}) 910``` 911