libjpeg decoding to BGR

Thomas Sampson picture Thomas Sampson · Apr 11, 2011 · Viewed 7.9k times · Source

I am using libjpeg to decode a jpeg image from disk to a memory buffer allocated on the heap. I use jpeg_read_scanlines to read and decode each scanline from the file. This is working perfectly, decoding each pixel as a 24-bit RGB value.

The problem is that I am using an additional third-party library which requires a buffer in BGR format (rather than RGB). When using this library I get odd results as the channels are in the wrong order.

Therefore, I would like to find a way to make libjpeg decode to BGR format rather than RGB. I have trawled the web and cannot find how to configure libjpeg to do this? I know I could do an additional pass over the memory buffer and re-order the colour channels manually, however the application I am working on is extremely time critical and must be as fast and as efficient as possible.

Answer

sam hocevar picture sam hocevar · Apr 11, 2011

Several solutions for you:

  • Do the transformation as suggested. If you work on groups of 4 pixels, you can do everything with three 32-bit reads and writes, bitmasks and shifts, and be very fast.
  • Modify libjpeg's YUV to RGB transformation or the stage just after so that it swaps R and B.
  • Use libjpeg-turbo. It is backwards compatible with libjpeg, has SIMD acceleration, and provides JCS_EXT_BGR and JCS_EXT_BGRX colorspaces.
  • Modify your source images so that their R and B channels are swapped. Sounds silly, but it requires zero source code modification.

Also, you say you are after speed yet you manipulate BGR data (instead of BGRX). This does not make much sense to me since aligning pixels on 32 bits boundaries is probably going to be much faster.