zl程序教程

您现在的位置是:首页 >  其他

当前栏目

libjpeg存文件

2023-04-18 15:48:20 时间
#include <cstdio>
#include <cstdlib>
#include "jpeglib.h"

int _imageWidth = 320;     // 生成的图像宽度
int _imageHeight = 240;    // 生成的图像高度
int _inputComponents = 1; // 生成的图像深度

try
{
    struct jpeg_compress_struct jcs;
    struct jpeg_error_mgr jem;

    jcs.err = jpeg_std_error(&jem);
    jpeg_create_compress(&jcs);

    FILE *fp = nullptr;

    if ((fp = fopen(path.c_str(), "wb")) != nullptr)
    {
        jpeg_stdio_dest(&jcs, fp);

        jcs.image_width = _imageWidth;
        jcs.image_height = _imageHeight;
        jcs.input_components = _inputComponents;

        if (_inputComponents == 1)
        {
            jcs.in_color_space = JCS_GRAYSCALE;
        }
        else
        {
            jcs.in_color_space = JCS_RGB;
        }

        jpeg_set_defaults(&jcs);
        jpeg_set_quality(&jcs, 90, TRUE);

        jpeg_start_compress(&jcs, TRUE);

        JSAMPROW rowPointer[1];
        long rowStride = _imageWidth * _inputComponents;
        JSAMPROW p = (JSAMPROW)buf;
        while (jcs.next_scanline < _imageHeight)
        {
            rowPointer[0] = &p[jcs.next_scanline * rowStride];
            (void)jpeg_write_scanlines(&jcs, rowPointer, 1);
        }

        jpeg_finish_compress(&jcs);

        fclose(fp);
        fp = nullptr;
    }

    jpeg_destroy_compress(&jcs);
}
catch (...)
{
    return false;
}