Rate This Document
Findability
Accuracy
Completeness
Readability

Usage Example

The following is an example of decoding a JPG image and converting it into AVIF and WebP formats.

  1. Create a main.cpp file and write the following sample code into it.
      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
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    #include <avif/avif.h>
    #include <iostream>
    #include <fstream>
    #include <vector>
    #include <turbojpeg.h>
    #include <png.h>
    #include <gif_lib.h>
    #include <vector>
    #include <map>
    #include <algorithm>
    #include <memory>
    #include <stdexcept>
    #include <wand/magick_wand.h>
    #include <webp/encode.h>
    // Decode a JPG file.
    static bool decodeJPGtoRGBA(const std::string& inputPath, std::vector<uint8_t>& rgbaData, int& width, int& height) {
        // Open a JPEG file.
        std::ifstream inputFile(inputPath, std::ios::binary | std::ios::ate);
        if (!inputFile) {
            std::cerr << "Failed to open the file: " << inputPath << std::endl;
            return false;
        }
        // Obtain the file size and read data.
        std::streamsize fileSize = inputFile.tellg();
        inputFile.seekg(0, std::ios::beg);
        std::vector<unsigned char> jpegData(fileSize);
        if (!inputFile.read(reinterpret_cast<char*>(jpegData.data()), fileSize)) {
            std::cerr << "Failed to read the file: " << inputPath << std::endl;
            return false;
        }
        // Create a TurboJPEG decoder instance.
        tjhandle handle = tjInitDecompress();
        if (!handle) {
            std::cerr << "Failed to initialize the TurboJPEG decoder" << std::endl;
            return false;
        }
        // Obtain the width, height, and pixel format of the JPEG image.
        int jpegSubsamp;
        if (tjDecompressHeader2(handle, jpegData.data(), jpegData.size(), &width, &height, &jpegSubsamp) != 0) {
            std::cerr << "Failed to parse the JPEG header: " << tjGetErrorStr() << std::endl;
            tjDestroy(handle);
            return false;
        }
        // Allocate the storage space for RGBA data.
        rgbaData.resize(width * height * 4); // 4 bytes per pixel (RGBA)
        // Decode JPEG data into RGBA format.
        if (tjDecompress2(handle, jpegData.data(), jpegData.size(), rgbaData.data(), width, 0, height, TJPF_RGBA, TJFLAG_FASTDCT) != 0) {
            std::cerr << "JPEG decoding failed: " << tjGetErrorStr() << std::endl;
            tjDestroy(handle);
            return false;
        }
        tjDestroy(handle);
        std::cout << "JPEG file decoded into the RGBA format" << std::endl;
        return true;
    }
    // Encode RGBA data into an AVIF file.
    bool encodeRGBAtoAVIF(const std::string& outputPath, const uint8_t* rgbaData, int width, int height) {
        // Create an AVIF encoder.
        avifEncoder* encoder = avifEncoderCreate();
        if (!encoder) {
            std::cerr << "Failed to create the AVIF encoder" << std::endl;
            return false;
        }
        // Set encoder parameters.
        encoder->maxThreads = 8; // Set the maximum number of threads.
        encoder->minQuantizer = 19; // Minimum quantizer
        encoder->maxQuantizer = 21; // Maximum quantizer
        encoder->minQuantizerAlpha = 0;
        encoder->maxQuantizerAlpha = 0;
        encoder->tileRowsLog2=3;
        encoder->tileColsLog2=3;
        encoder->speed = 8; // Encoding speed
       encoder->codecChoice = AVIF_CODEC_CHOICE_AOM;
        avifImage* image = avifImageCreate(width, height, 8, AVIF_PIXEL_FORMAT_YUV420);
        if (!image) {
            std::cerr << "Failed to create an AVIF image" << std::endl;
            avifEncoderDestroy(encoder);
            return false;
        }
        image->yuvFormat = AVIF_PIXEL_FORMAT_YUV420;
        image->depth = 8;
        image->width = width;
        image->height = height;
        avifRGBImage rgbImage;
        avifRGBImageSetDefaults(&rgbImage, image);
        rgbImage.format = AVIF_RGB_FORMAT_RGBA;
        rgbImage.depth = 8;
        rgbImage.width = width;
        rgbImage.height = height;
        rgbImage.rowBytes = width * 4;
        rgbImage.pixels = const_cast<uint8_t*>(rgbaData);
        if (avifImageRGBToYUV(image, &rgbImage) != AVIF_RESULT_OK) {
            std::cerr << "Failed to convert RGBA data to YUV" << std::endl;
            avifImageDestroy(image);
            avifEncoderDestroy(encoder);
            return false;
        }
        avifRWData output = AVIF_DATA_EMPTY;
        if (avifEncoderWrite(encoder, image, &output) != AVIF_RESULT_OK) {
            std::cerr << "Encoding failed" << std::endl;
            avifImageDestroy(image);
            avifEncoderDestroy(encoder);
            return false;
        }
        std::ofstream outFile(outputPath, std::ios::binary);
        if (!outFile.write(reinterpret_cast<char*>(output.data), output.size)) {
            std::cerr << "Failed to write the file" << std::endl;
            avifRWDataFree(&output);
            avifImageDestroy(image);
            avifEncoderDestroy(encoder);
            return false;
        }
        avifRWDataFree(&output);
        avifImageDestroy(image);
        avifEncoderDestroy(encoder);
        std::cout << "AVIF file generated: " << outputPath << std::endl;
        return true;
    }
    // Convert an AVIF image into the RGBA format.
    bool decodeAVIFtoRGBA(const std::string& inputPath, std::vector<uint8_t>& rgbaData, int& width, int& height) {
        // Open an AVIF file.
        std::ifstream inFile(inputPath, std::ios::binary | std::ios::ate);
        if (!inFile) {
            std::cerr << "Failed to open the AVIF file: " << inputPath << std::endl;
            return false;
        }
        std::streamsize fileSize = inFile.tellg();
        inFile.seekg(0, std::ios::beg);
        std::vector<uint8_t> fileData(fileSize);
        if (!inFile.read(reinterpret_cast<char*>(fileData.data()), fileSize)) {
            std::cerr << "Failed to read the AVIF file: " << inputPath << std::endl;
            return false;
        }
        // Create an AVIF decoder.
        avifDecoder* decoder = avifDecoderCreate();
        if (!decoder) {
            std::cerr << "Failed to create the AVIF decoder" << std::endl;
            return false;
        }
        avifDecoderSetIOMemory(decoder, fileData.data(), fileSize);
        if (avifDecoderParse(decoder) != AVIF_RESULT_OK) {
            std::cerr << "Failed to parse AVIF data" << std::endl;
            avifDecoderDestroy(decoder);
            return false;
        }
        if (avifDecoderNextImage(decoder) != AVIF_RESULT_OK) {
            std::cerr << "Failed to decode the AVIF image" << std::endl;
            avifDecoderDestroy(decoder);
            return false;
        }
        const avifImage* image = decoder->image;
        avifRGBImage rgbImage;
        avifRGBImageSetDefaults(&rgbImage, image);
        rgbImage.format = AVIF_RGB_FORMAT_RGBA;
        rgbImage.depth = 8;
        rgbImage.rowBytes = image->width * 4;
        width = image->width;
        height = image->height;
        rgbaData.resize(rgbImage.rowBytes * image->height);
        rgbImage.pixels = rgbaData.data();
        if (avifImageYUVToRGB(image, &rgbImage) != AVIF_RESULT_OK) {
            std::cerr << "Failed to convert YUV data to RGBA" << std::endl;
            avifDecoderDestroy(decoder);
            return false;
        }
        avifDecoderDestroy(decoder);
        std::cout << "AVIF file decoded into the RGBA format" << std::endl;
        return true;
    }
    // Encode RGBA data into a WebP file.
    bool encodeRGBAtoWebP(const std::string& outputPath, const uint8_t* rgbaData, int width, int height) {
        if (!rgbaData || width <= 0 || height <= 0) {
            std::cerr << "Invalid input parameters" << std::endl;
            return false;
        }
        // Set encoding parameters.
        WebPConfig config;
        if (!WebPConfigInit(&config)) {
            std::cerr << "Failed to initialize WebPConfig" << std::endl;
            return false;
        }
        config.lossless = 0;      // Use lossy compression.
        config.quality = 75.0f;   // Set the compression quality.
        config.method = 6;        // Encoding speed (A larger value indicates a slower speed but a higher compression rate.)
        // Convert data from RGBA to WebP.
        WebPPicture picture;
        if (!WebPPictureInit(&picture)) {
            std::cerr << "Failed to initialize WebPPicture" << std::endl;
            return false;
        }
        picture.width = width;
        picture.height = height;
        picture.use_argb = 0; // Use the YUV mode for encoding.
        // Import RGBA data to WebPPicture.
        if (!WebPPictureImportRGBA(&picture, rgbaData, width * 4)) {
            std::cerr << "Failed to import RGBA data" << std::endl;
            WebPPictureFree(&picture);
            return false;
        }
        // Output a memory structure.
        WebPMemoryWriter writer;
        WebPMemoryWriterInit(&writer);
        picture.writer = WebPMemoryWrite;
        picture.custom_ptr = &writer;
        // Perform encoding.
        if (!WebPEncode(&config, &picture)) {
            std::cerr << "WebP encoding failed. Error code: " << picture.error_code << std::endl;
            WebPPictureFree(&picture);
            WebPMemoryWriterClear(&writer);
            return false;
        }
        // Write the file.
        std::ofstream outFile(outputPath, std::ios::binary);
        if (!outFile.write(reinterpret_cast<char*>(writer.mem), writer.size)) {
            std::cerr << "Failed to write the file" << std::endl;
            WebPPictureFree(&picture);
            WebPMemoryWriterClear(&writer);
            return false;
        }
        WebPPictureFree(&picture);
        WebPMemoryWriterClear(&writer);
        std::cout << "WebP file generated: " << outputPath << std::endl;
        return true;
    }
    int main()
    {
        std::vector<uint8_t> rgbaData;
        int width, height;
        std::string outputPathavif = "./1.avif";
        std::string outputPathWebp = "./1.webp";
        std::string inputPath = "/home/imgtest/1.jpg";
        bool decode = decodeJPGtoRGBA(inputPath, rgbaData, width, height);
        bool encodeAvif = encodeRGBAtoAVIF(outputPathavif, rgbaData.data(), width, height); // Convert to AVIF.
        bool encodeWebp = encodeRGBAtoWebP(outputPathWebp, rgbaData.data(), width, height); // Convert to WebP.
        return 0;
    }
    
  2. Perform the compilation.
    1
    g++ -std=c++17 -I/opt/jdimg/include -I/opt/jdimg/include/GraphicsMagick -I/opt/jdimg/include/webp     -L/opt/jdimg/lib -L/opt/jdimg/lib64     -lavif -lturbojpeg -lpng -lgif -lwebp     -lGraphicsMagick -lGraphicsMagick++ -lGraphicsMagickWand     -Wl,-rpath,/opt/jdimg/lib64  main.cpp -o main && ./main