VideoSender/jpeg_img.cpp

106 lines
3.0 KiB
C++

#include "jpeg_img.h"
#include <iostream>
#include <jpeglib.h>
#include <jerror.h>
Image decompressJpegImage(const unsigned char* buffer, size_t size)
{
struct jpeg_decompress_struct info; //for our jpeg info
struct jpeg_error_mgr err; //the error handler
info.err = jpeg_std_error( &err );
jpeg_create_decompress( &info ); //fills info structure
jpeg_mem_src(&info, buffer, size);
if(jpeg_read_header(&info, true) != JPEG_HEADER_OK)
std::cerr<<"Could not read jpeg header";
jpeg_start_decompress( &info );
Image image;
image.width = info.output_width;
image.height = info.output_height;
image.channels = info.num_components; // 3 = RGB, 4 = RGBA
// read RGB(A) scanlines one at a time into jdata[]
image.data = std::shared_ptr<unsigned char>(new unsigned char[image.size()], std::default_delete<unsigned char[]>());
unsigned char* rowptr;
while(info.output_scanline < image.height)
{
rowptr = image.data.get() + info.output_scanline * image.width * image.channels;
jpeg_read_scanlines( &info, &rowptr, 1 );
}
jpeg_finish_decompress( &info );
return image;
}
Image decompressJpegImage(FILE *file)
{
struct jpeg_decompress_struct info; //for our jpeg info
struct jpeg_error_mgr err; //the error handler
info.err = jpeg_std_error( &err );
jpeg_create_decompress( &info ); //fills info structure
jpeg_stdio_src( &info, file );
jpeg_read_header( &info, true );
jpeg_start_decompress( &info );
Image image;
image.width = info.output_width;
image.height = info.output_height;
image.channels = info.num_components; // 3 = RGB, 4 = RGBA
// read RGB(A) scanlines one at a time into jdata[]
image.data = std::shared_ptr<unsigned char>(new unsigned char[image.size()], std::default_delete<unsigned char[]>());
unsigned char* rowptr;
while ( info.output_scanline < image.height )
{
rowptr = image.data.get() + info.output_scanline * image.width * image.channels;
jpeg_read_scanlines( &info, &rowptr, 1 );
}
jpeg_finish_decompress( &info );
fclose( file );
return image;
}
void compressJpegImage(FILE *file, Image *image)
{
struct jpeg_compress_struct info;
struct jpeg_error_mgr err;
info.err = jpeg_std_error( &err );
jpeg_create_compress(&info);
jpeg_stdio_dest(&info, file);
/* Setting the parameters of the output file here */
info.image_width = image->width;
info.image_height= image->height;
info.input_components = image->channels;
info.in_color_space = JCS_RGB;
jpeg_set_defaults( &info );
/* Now do the compression .. */
jpeg_start_compress( &info, TRUE );
unsigned char* rowptr;
while ( info.next_scanline < image->height )
{
rowptr = image->data.get() + info.next_scanline * image->width * image->channels;
jpeg_write_scanlines( &info, &rowptr, 1 );
}
jpeg_finish_compress( &info );
jpeg_destroy_compress( &info );
}