库安装就不说了,我是直接下载编译好的库
Independent JPEG Group (ijg.org)
这个需要自己编译
可以使用的代码
#include <stdio.h>
#include <jpeglib.h>
#include <stdlib.h>
void compress_jpeg(const char* input_filename, const char* output_filename, int quality) {
struct jpeg_decompress_struct cinfo_in;
struct jpeg_compress_struct cinfo_out;
struct jpeg_error_mgr jerr_in, jerr_out;
FILE* input_file = NULL;
errno_t err1 = fopen_s(&input_file, input_filename, "rb");
if (err1) {
fprintf(stderr, "Error opening input file.\n");
exit(1);
}
FILE* output_file = NULL;
errno_t err2 = fopen_s(&output_file, output_filename, "wb");
if (err2) {
fprintf(stderr, "Error opening output file.\n");
exit(1);
}
if (!input_file || !output_file) {
fprintf(stderr, "Error opening files.\n");
exit(1);
}
// Decompress
cinfo_in.err = jpeg_std_error(&jerr_in);
jpeg_create_decompress(&cinfo_in);
jpeg_stdio_src(&cinfo_in, input_file);
jpeg_read_header(&cinfo_in, TRUE);
jpeg_start_decompress(&cinfo_in);
JSAMPLE* buffer = (JSAMPLE*)malloc(cinfo_in.output_width * cinfo_in.output_components);
// Compress
cinfo_out.err = jpeg_std_error(&jerr_out);
jpeg_create_compress(&cinfo_out);
jpeg_stdio_dest(&cinfo_out, output_file);
cinfo_out.image_width = cinfo_in.image_width;
cinfo_out.image_height = cinfo_in.image_height;
cinfo_out.input_components = cinfo_in.num_components;
cinfo_out.in_color_space = cinfo_in.out_color_space;
jpeg_set_defaults(&cinfo_out);
jpeg_set_quality(&cinfo_out, quality, TRUE);
jpeg_start_compress(&cinfo_out, TRUE);
while (cinfo_in.output_scanline < cinfo_in.output_height) {
jpeg_read_scanlines(&cinfo_in, &buffer, 1);
jpeg_write_scanlines(&cinfo_out, &buffer, 1);
}
jpeg_finish_decompress(&cinfo_in);
jpeg_finish_compress(&cinfo_out);
jpeg_destroy_decompress(&cinfo_in);
jpeg_destroy_compress(&cinfo_out);
free(buffer);
fclose(input_file);
fclose(output_file);
}
int main() {
const char* input = R"(C:\Users\Administrator\Desktop\ThreeData\weixingOBJ\tex\Tile_+000_+000_23_00013300_0000.jpg)";
const char* output = R"(C:\Users\Administrator\Desktop\ThreeData\weixingOBJ\tex\outlibjpeg.jpg)";
compress_jpeg(input, output, 50); // 50 is the quality, it can be from 0 to 100.
printf("Compression done. Check %s\n", output);
return 0;
}
顺便把这个库集成到OSG库中