简体   繁体   English

Jpeg Turbo 适用于彩色但不适用于灰度

[英]Jpeg Turbo works with Color but not greyscale

I am wrote a function with Jpeg Turbo to allow it to do compression and it looks something like this:我用 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;
}

It works great with RGB images, but fails on greyscale images with Error encoding image: Unsupported color conversion request它适用于 RGB 图像,但在灰度图像上失败, Error encoding image: Unsupported color conversion request

I don't know what I am doing wrong with the library我不知道我在图书馆做错了什么

I recently had the same issue (with similar code that writes both RGB and grayscale images), and it took me a while to find the culprit:我最近遇到了同样的问题(使用类似的代码编写 RGB 和灰度图像),我花了一段时间才找到罪魁祸首:

The sub-sampling that is applied must match the color space: for actual color images, using any of the TJSAMP_4xx constants (eg TJSAMP_420 ) is a valid choice, but for grayscale images the sub-sampling must be set to TJSAMP_GRAY .应用的子采样必须与色彩空间匹配:对于实际的彩色图像,使用任何TJSAMP_4xx常量(例如TJSAMP_420 )都是有效的选择,但对于灰度图像,子采样必须设置为TJSAMP_GRAY

With that libjpeg-turbo will happily store grayscale JPEG files using the tjCompress2() API.有了这个 libjpeg-turbo 将很乐意使用tjCompress2() API 存储灰度 JPEG 文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM