Using ImagePacker to Encode Pictures
Image encoding refers to the process of encoding a picture into an image in different formats (only in JPEG and HEIF currently) for subsequent processing, such as storage and transmission.
How to Develop
Read the API reference for APIs related to image encoding.
-
Import the required modules.
// Import the required modules. import { image } from '@kit.ImageKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; import { fileIo as fs } from '@kit.CoreFileKit'; import { resourceManager } from '@kit.LocalizationKit'; -
Create an ImagePacker object.
const imagePackerApi = image.createImagePacker(); -
Set the encoding output stream and encoding parameters.
format indicates the image encoding format, and quality indicates the image quality. The value range is [0, 100], and the value 100 indicates the optimal quality.
NOTE
According to the MIME protocol, the standard encoding format is image/jpeg. When the APIs provided by the image module are used for encoding, PackingOption.format must be set to image/jpeg. The file name extension of the encoded image file can be .jpg or .jpeg, and the file can be used on platforms that support image/jpeg decoding.
let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 95, desiredDynamicRange: image.PackingDynamicRange.AUTO, needsPackProperties: true };
Encoding Images into File Streams
Encode the image and save the encoded data. Before encoding, you need to obtain a Picture object through decoding. For details, see Using ImageSource to Decode Pictures.
async function packing(picture: image.Picture, packOpts: image.PackingOption) {
const imagePackerApi = image.createImagePacker();
try {
let data = await imagePackerApi.packing(picture, packOpts);
copyData = data;
console.info('Succeeded in packing the image.');
} catch (error) {
console.error('Failed to pack the picture to data. And the error is: ' + error);
}
}
Encoding Images into Files
Before encoding, you need to obtain a Picture object through decoding. For details, see Using ImageSource to Decode Pictures.
During encoding, you can define the output file path and write the encoded memory data to the file.
async function packToFile(picture: image.Picture, packOpts: image.PackingOption, context: Context) {
const path : string = context.cacheDir + '/picture.jpg';
let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
const imagePackerApi = image.createImagePacker();
try {
await imagePackerApi.packToFile(picture, file.fd, packOpts);
} catch (error) {
console.error('Failed to pack the picture to file. And the error is: ' + error);
}
}