55 lines
1.5 KiB
C++
55 lines
1.5 KiB
C++
// Copyright (2019-2024) Paul Scherrer Institute
|
|
|
|
#include <vector>
|
|
#include <cstdio>
|
|
#include <cstdint>
|
|
#include <cmath>
|
|
#include <jpeglib.h>
|
|
|
|
#include "../common/JFJochException.h"
|
|
#include "JFJochJPEG.h"
|
|
|
|
|
|
std::string WriteJPEGToMem(const std::vector<uint8_t> &input, size_t width, size_t height, int quality) {
|
|
unsigned char *buf = nullptr;
|
|
unsigned long buf_size = 0;
|
|
|
|
if (width * height * 3 != input.size())
|
|
throw JFJochException(JFJochExceptionCategory::InputParameterInvalid, "Invalid array size for WriteJPEG");
|
|
|
|
struct jpeg_compress_struct cinfo;
|
|
struct jpeg_error_mgr jerr;
|
|
|
|
cinfo.err = jpeg_std_error(&jerr);
|
|
jpeg_create_compress(&cinfo);
|
|
jpeg_mem_dest(&cinfo, &buf, &buf_size);
|
|
|
|
cinfo.image_width = width;
|
|
cinfo.image_height = height;
|
|
cinfo.input_components = 3;
|
|
cinfo.in_color_space = JCS_RGB;
|
|
|
|
jpeg_set_defaults(&cinfo);
|
|
/*set the quality [0..100] */
|
|
jpeg_set_quality (&cinfo, quality, true);
|
|
jpeg_simple_progression(&cinfo);
|
|
jpeg_start_compress(&cinfo, true);
|
|
|
|
JSAMPROW row_pointer; /* pointer to a single row */
|
|
|
|
while (cinfo.next_scanline < cinfo.image_height) {
|
|
row_pointer = (JSAMPROW) (input.data() + cinfo.next_scanline*(sizeof(char)*3)*width);
|
|
jpeg_write_scanlines(&cinfo, &row_pointer, 1);
|
|
}
|
|
|
|
jpeg_finish_compress(&cinfo);
|
|
jpeg_destroy_compress(&cinfo);
|
|
|
|
std::string ret;
|
|
if (buf_size > 0)
|
|
ret = std::string((char *)buf, buf_size);
|
|
free(buf);
|
|
|
|
return ret;
|
|
}
|