Menu Home

使用jpeglib压缩图片

#include <jpeglib.h>
void writeJPEG(unsigned char* pixs, int  width, int height, char* file) {
    struct jpeg_compress_struct jcs;
    struct jpeg_error_mgr jem;
    jcs.err = jpeg_std_error(&jem);
    jpeg_create_compress(&jcs);
    FILE* fp = fopen(file, "wb");
    if(fp == NULL) {
        perror("writeJPEG");
        return;
    }

    jpeg_stdio_dest(&jcs, fp);
    jcs.image_width = width;
    jcs.image_height = height;
    jcs.input_components = 3; //RGB
    jcs.in_color_space = JCS_RGB;
    jpeg_set_defaults(&jcs);
    jpeg_set_quality(&jcs, 100, TRUE); //输出图片质量

    jpeg_start_compress(&jcs, TRUE);
    JSAMPROW row_pointer[1];
    int row_stride;
    row_stride = jcs.image_width * 3; //RGB

    while(jcs.next_scanline < jcs.image_height) {
        row_pointer[0] = &pixs[jcs.next_scanline * row_stride];
        jpeg_write_scanlines(&jcs, row_pointer, 1);
    }
    
    jpeg_finish_compress(&jcs);
    jpeg_destroy_compress(&jcs);
    fclose(fp);
}

Categories: C/C++ 图形学

Tagged as:

lnmcc