61 lines
1.7 KiB
C++
61 lines
1.7 KiB
C++
// SPDX-FileCopyrightText: 2024 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
|
|
// SPDX-License-Identifier: GPL-3.0-only
|
|
|
|
#include <vector>
|
|
#include <cstdio>
|
|
#include <cstdint>
|
|
#include <cmath>
|
|
#include <jpeglib.h>
|
|
|
|
#include "../common/JFJochException.h"
|
|
#include "../common/CompressedImage.h"
|
|
#include "JFJochJPEG.h"
|
|
|
|
|
|
std::string WriteJPEGToMem(const CompressedImage& image, int quality) {
|
|
unsigned char *buf = nullptr;
|
|
unsigned long buf_size = 0;
|
|
|
|
if (image.GetMode() != CompressedImageMode::RGB)
|
|
throw JFJochException(JFJochExceptionCategory::InputParameterInvalid,
|
|
"Only RGB images allowed for JPEG saving");
|
|
|
|
std::vector<uint8_t> buffer;
|
|
image.GetUncompressed(buffer);
|
|
|
|
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 = image.GetWidth();
|
|
cinfo.image_height = image.GetHeight();
|
|
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) (buffer.data() + cinfo.next_scanline*(sizeof(char)*3)*image.GetWidth());
|
|
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;
|
|
}
|