Sunday, May 15, 2011

jpeglib example c c++

A jpeglib example is explained in this article. Jpeglib is an open source library that is used to encode and decode JPEG image format. The library is fairly simple to use. See following example for detailed decoding procedure. [jpeglib example]


Step 1. Include files for jpeglib example

#include "jinclude.h"
#include "jpeglib.h"

Step 2. Decoding procedure.

a_pFilename -> jpeg filename.

a_pBuffer -> pointer to image buffer. It's allocated inside the read() function.

bool read(char *a_pFilename, JSAMPLE **a_pBuffer)
{

// Data strucure required for decoding JPEG file.
//
struct jpeg_decompress_struct cInfo;
struct jpeg_error_mgr cErrMgr;

FILE *pFile;
int iRowStride, i;
JSAMPARRAY pRows;

// Check the filename is valid.
//
if( !a_pFilename )
return false;

// open the file in binary mode.
//
pFile = fopen(a_pFilename, "rb");
if( !pFile )
return false;

// 1. Install error manager.
//
cInfo.err = jpeg_std_error(&cErrMgr);

// 2. Create JPEG decompressor object.
//
jpeg_create_decompress(&cInfo);

// 3. Specify the data source.
//
jpeg_stdio_src(&cInfo, pFile);

// 4. Read JPEG Header to extract image information.
//
(void) jpeg_read_header(&cInfo, TRUE);

// From now on, you can access information on the jpeg image by 
// referencing fields of cInfo object.
//

// 5. Set Target Image Format. Here we store the decoded image in JCS_RGB format.
//
cInfo.out_color_space = JCS_RGB;

// 6. Initiate decompress procedure.
//
(void) jpeg_start_decompress(&cInfo);

// 7. Allocate temporary buffer for decoding.
iRowStride = cInfo.output_width * cInfo.output_components;
(*a_pBuffer) = new JSAMPLE[ iRowStride * cInfo.output_height ];
if( !(*a_pBuffer) )
{
// Allocation failed.
jpeg_destroy_decompress(&cInfo);
fclose(pFile);
return false;
}

// Assign row buffers.
//
pRows = new JSAMPROW[ 1 ];
if( !pRows )
{
// Allocation failed.
delete[] (*a_pBuffer);
(*a_pBuffer) = NULL;
jpeg_destroy_decompress(&cInfo);
fclose(pFile);
return false;
}

// Decoding loop:
//
i = 0;
while (cInfo.output_scanline < cInfo.output_height)
{
// Decode it !
pRows[0] = (JSAMPROW)( (*a_pBuffer) + iRowStride * i); // set row buffer
(void) jpeg_read_scanlines(&cInfo, pRows, 1); // decode
i++;
}

// 8. Finish decompression.
//
(void) jpeg_finish_decompress(&cInfo);

// 9. Reclaim resources and return.
//
delete[] pRows;
jpeg_destroy_decompress(&cInfo);
fclose(pFile);

return true;
}