Image Encoding

Function Description

Encodes the Image object output by the API into a .jpg image in the memory or saves the Image object to a specified path.

For details about the API, see Encode.

API Calling Process

Prepare the Image object to be encoded in advance. The Image object can be output to a local image or the memory by using the image decoding or image processing APIs (such as the APIs for cropping, resizing, and padding).

The process of calling image encoding APIs is as follows:

Figure 1 Process of calling image encoding APIs

Key steps are demonstrated as follows:

  1. Perform global initialization by calling MxInit().
  2. Construct and initialize ImageProcessor.

    Construct an ImageProcessor object and initialize the channel by calling InitJpegEncodeChannel(). If you skip this API, ImageProcessor automatically initializes the channel before encoding.

  3. Call the image decoding API to decode the input image.

    Decode the image based on services to generate a codable Image object. Subsequently, the image can be processed by using the image processing APIs to generate a final Image object to be encoded.

  4. Encode the input image by calling Encode().

    Output the image data to a file or to the memory based on the service requirements.

  5. Deinitialize the initialized global resources by calling MxDeInit().

Sample Code

The following is a code example of key steps of functions and features, which is for reference only and cannot be directly copied for compilation or running.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Initialization
MxInit();
{
    // Construct the image processing class.
    ImageProcessor imageProcessor(deviceId);

    // Image decoding/Image processing for Image generation
    // Decoded image class
    Image decodedImage;
    // Perform decoding based on the image path.
    APP_ERROR ret = imageProcessor.Decode(imagePath, decodedImage);
    if (ret != APP_ERR_OK) {
        std::cout << "Decode failed." << std::endl;
    }
    // Image class after image processing
    Image resizedImage;
    // Image processing (resizing)
    ret = imageProcessor.Resize(decodedImage, Size(416, 416), resizedImage, Interpolation::HUAWEI_HIGH_ORDER_FILTER);
    if (ret != APP_ERR_OK) {
        std::cout << "Resize failed." << std::endl;
    }

    // (Optional) Initialize the encoding channel.
    JpegEncodeChnConfig jpegEncodeChnConfig;
    JpegEncodeChnConfig.maxPicWidth = 4096;
    JpegEncodeChnConfig.maxPicHeight = 4096;
    imageProcessor.InitJpegEncodeChannel(jpegEncodeChnConfig);

    // Image encoding
    ret = imageProcessor.Encode(resizedImage,"encode.jpg");
    if (ret != APP_ERR_OK) {
        std::cout << "Encode failed." << std::endl;
    }
}
// Deinitialization
MxDeInit();