GreycLab/CImg

How to read image from memory file (not pixels array)

Closed this issue · 6 comments

How to read image from memory (bytes of image file), something like this:

0000h: 89 50 4E 47 0D 0A 1A 0A 00 00 00 0D 49 48 44 52 ‰PNG........IHDR
0010h: 00 00 00 4E 00 00 00 20 08 06 00 00 00 BC 54 4E ...N... .....¼TN
0020h: 37 00 00 00 20 63 48 52 4D 00 00 7A 26 00 00 80 7... cHRM..z&..€
0030h: 84 00 00 FA 00 00 00 80 E8 00 00 75 30 00 00 EA „..ú...€è..u0..ê
0040h: 60 00 00 3A 98 00 00 17 70 9C BA 51 3C 00 00 00 `..:˜...pœºQ<...
0050h: 04 67 41 4D 41 00 00 B1 8F 0B FC 61 05 00 00 00 .gAMA..±
.....................

As I tried, following function only can read pixels data from memory, not file data.
It will treat the image HEAD as pixels data.

CImg ( const t *const values,
const unsigned int size_x,
const unsigned int size_y = 1,
const unsigned int size_z = 1,
const unsigned int size_c = 1,
const bool is_shared = false
)

The reason why I want to read image from memory is that: users will send the bytes of images to my web server, I don't want to save the image to a temp file and then read from that file(disk i/o is the bottleneck).

Any comments are welcome, thanks!

Have you considered writing and reading from a RAM disk?

@aalbiol
Thanks for your suggestion, but there are extra resource costs even writing and reading from a RAM disk. Also extra work to maintain the RAM disk.

Anyhow, I write and read from disk for now...
And I also plan to add memory reading support for CImg when free (maybe in the long future).

@lofrank pretty sure you just want to use fmemopen (http://pubs.opengroup.org/onlinepubs/9699919799/functions/fmemopen.html) to create a FILE* from memory and then use the standard CImg load functions like load_cimg(std::FILE *const file).

Thanks for the suggestion @Meekohi , I wasn't aware of this function, I'll probably make some tests with it next week :)

Dian8 commented

Does somebody know good fmemopen() implementation for visual studio?

@Dian8
I can't find a windows version fmemopen() after a lot of searches.

Here are three solutions to read image from memory buffer on windows (as I figure out):

  1. Use OpenCv library
  2. Decode image by yourself (need different decoders for different image types), these decoders can be copied from CImg, the only difference is that CImg read bytes from file instead of memory
  3. (Not suggested) Save to disk first, then read from file