RAII Wrapper for libjpeg Compression/Decompression

To facilitate resource cleanup within libjpeg encoding/decoding functions, the following classes implement RAII wrappers for the jpeg_decompress_struct and jpeg_compress_struct structures.

RAII is a C++ concept which helps to ensure that all resources are correctly deinitialized/released even in case of error/exceptions.

Usage example:

jpeg_decompress_struct_wrapper cinfo;
jpeg_decompress_struct* pcinfo = cinfo;
jpeg_win32_src_mgr src_data;
 
jpeg_win32_src( cinfo, &src_data, szFilename );
jpeg_read_header( cinfo, TRUE ); 
pcinfo->dct_method = JDCT_IFAST;
/* ... */

No calls to jpeg_destroy_decompress() are necessary, stack unwinding will ensure that the jpeg_decompress_struct will be automatically destroyed, even if the encoding/decoding routine has several exit/return paths.
Since the wrapper class implements an operator for jpeg_decompress_struct*, the instance can be passed as a parameter instead of „&cinfo“.

This is the wrapper for jpeg_decompress_struct:

class jpeg_decompress_struct_wrapper
{
public:
    jpeg_decompress_struct_wrapper()
    {
        jpeg_create_decompress( &this->cinfo );
    }
 
    ~jpeg_decompress_struct_wrapper()
    {
        jpeg_destroy_decompress( &this->cinfo );
    }
 
    operator jpeg_decompress_struct*()
    {
        return &this->cinfo;
    }
private:
    jpeg_decompress_struct cinfo;
};

Wrapper for jpeg_compress_struct:

class jpeg_compress_struct_wrapper
{
public:
    jpeg_compress_struct_wrapper()
    {
        jpeg_create_compress( &this->cinfo );
    }
 
    ~jpeg_compress_struct_wrapper()
    {
        jpeg_destroy_compress( &this->cinfo );
    }
 
    operator jpeg_compress_struct*()
    {
        return &this->cinfo;
    }
private:
    jpeg_compress_struct cinfo;
};

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.