I'm practicing using the libjpeg library for a separate project, and I just wanted to generate a blue 100x100 jpeg image file utilizing libjpeg. I followed each step in their documentation, and I get a segmentation fault at jpeg_finish_compress(). I've utilized gdb to dig deeper into what's happening, and I'm having issues seeing what happens between the initial call to the function and the next step (within jpeg_finish_compress()). Here's my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include "jpeglib.h"
int height = 100;
int width = 100;
int i, j;
int main() {
//init the image
unsigned char image[height][width][3];
for(i = 0; i < height; i++) {
for(j = 0; j < width; j++) {
image[i][j][0] = 0x0;
image[i][j][1] = 0x0;
image[i][j][2] = 0xFF;
}
}
//Create compression objects
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);
//Choose a destination and add error handling
FILE *outfile = (FILE*) malloc(sizeof(FILE));
char* filename = "test.jpeg";
if(outfile == fopen(filename, "wb")) {
fprintf(stderr, "can't open %s\n", filename);
exit(1);
}
jpeg_stdio_dest(&cinfo, outfile);
//Compression parameters
cinfo.image_width = width;
cinfo.image_height = height;
cinfo.input_components = 3; //RGB. 1 if grayscale
cinfo.in_color_space = JCS_RGB; //Could be JCS_GRAYSCALE also
//Note: There are other compression parameters, but for most purposes, you can use:
jpeg_set_defaults(&cinfo);
//DO the compression
jpeg_start_compress(&cinfo, TRUE);
JSAMPROW row_pointer[1]; //pointer to a row with 12-bit precision
while(cinfo.next_scanline < cinfo.image_height) {
row_pointer[0] = *image[cinfo.next_scanline];
jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
jpeg_finish_compress(&cinfo);
fclose(outfile); //close the file, responsibly
jpeg_destroy_compress(&cinfo);
}
I'm thinking it has something to do with the way I've structures the image variable, but it also could be that I'm using the library incorrectly. What exactly does jpeg_finish_compress do, and how can I get a jpeg from a set of RGB data?