Image encoding refers to the process of encoding a pixel map into an archived image in different formats (only in JPEG, WebP, and PNG currently) for subsequent processing, such as storage and transmission.
// Import the required module. import image from '@ohos.multimedia.image'; 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 ranges from 0 to 100, and the value 100 indicates the optimal quality.
let packOpts : image.PackingOption = { format:"image/jpeg", quality:98 }; Encode the image and save the encoded image.
Method 1: Use PixelMap for encoding.
import {BusinessError} from '@ohos.base'
imagePackerApi.packToData(pixelMap, packOpts).then( (data : ArrayBuffer) => {
// data is the file stream obtained after packing. You can write the file and save it to obtain an image.
}).catch((error : BusinessError) => {
console.error('Failed to pack the image. And the error is: ' + error);
}) Method 2: Use ImageSource for encoding.
import {BusinessError} from '@ohos.base'
imagePackerApi.packToData(imageSource, packOpts).then( (data : ArrayBuffer) => {
// data is the file stream obtained after packing. You can write the file and save it to obtain an image.
}).catch((error : BusinessError) => {
console.error('Failed to pack the image. And the error is: ' + error);
});