我用Jpeg Turbo编写了一个函数,允许它进行压缩,它看起来像这样:
bool JPEGCompress::compress(const uint8_t* data, size_t width, size_t height, ImageFrame::image_type type, std::string& out)
{
// Prealloc if not
out.reserve(1 << 24); // Preallocate 16 MB output buffer
// Allocate memory for compressed output
int subsamp = TJSAMP_420;
auto outsize_max = tjBufSize(width, height, subsamp);
if (size_t(-1) == outsize_max) {
fmt::print("Size out of bounds: w={} h={} ss={}n", width, height, subsamp);
return false;
}
out.resize(outsize_max);
// Select Pixel Format
int pix_fmt = -1;
if(type == ImageFrame::image_type::ImageColor)
pix_fmt = TJPF_RGB;
else if(type == ImageFrame::image_type::ImageGray)
pix_fmt = TJPF_GRAY;
else{
fmt::print("Compression doesn't work for this format: {}", ImageFrame::convEnum(type));
return false;
}
// Compress
auto outptr = (uint8_t*) out.data();
auto outsize = outsize_max;
if (-1 == tjCompress2(
compressor_, data, width, 0, height, pix_fmt,
&outptr, &outsize, subsamp, quality_, TJFLAG_NOREALLOC)) {
fmt::print("Error encoding image: {}n", tjGetErrorStr2(compressor_));
return false;
}
out.resize(outsize);
return true;
}
它适用于RGB图像,但在具有Error encoding image: Unsupported color conversion request
我不知道我把图书馆的做错了什么
我最近遇到了同样的问题(使用类似的代码编写RGB和灰度图像(,我花了一段时间才找到罪魁祸首:
应用的子采样必须与颜色空间匹配:对于实际的彩色图像,使用任何TJSAMP_4xx
常数(例如TJSAMP_420
(都是有效的选择,但对于灰度图像,子采样必须设置为TJSAMP_GRAY
。
有了它,libjpeg-turbo将很高兴地使用tjCompress2()
API存储灰度JPEG文件。