Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading an image file in C/C++ [closed]

Tags:

c++

c

jpeg

I need to read an image file in C/C++. It would be very great, if some one can post the code for me.

I work on gray scale images and the images are JPEG. I would like to read the images into a 2D array which will make my work easy.

like image 871
skyrulz Avatar asked Jan 16 '10 06:01

skyrulz


2 Answers

If you decide to go for a minimal approach, without libpng/libjpeg dependencies, I suggest using stb_image and stb_image_write, found here.

It's as simple as it gets, you just need to place the header files stb_image.h and stb_image_write.h in your folder.

Here's the code that you need to read images:

#include <stdint.h>  #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h"  int main() {     int width, height, bpp;      uint8_t* rgb_image = stbi_load("image.png", &width, &height, &bpp, 3);      stbi_image_free(rgb_image);      return 0; } 

And here's the code to write an image:

#include <stdint.h>  #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h"  #define CHANNEL_NUM 3  int main() {     int width = 800;      int height = 800;      uint8_t* rgb_image;     rgb_image = malloc(width*height*CHANNEL_NUM);      // Write your code to populate rgb_image here      stbi_write_png("image.png", width, height, CHANNEL_NUM, rgb_image, width*CHANNEL_NUM);      return 0; } 

You can compile without flags or dependencies:

g++ main.cpp 

Other lightweight alternatives include:

  • lodepng to read and write png files
  • jpeg-compressor to read and write jpeg files
like image 186
Jaime Ivan Cervantes Avatar answered Sep 23 '22 16:09

Jaime Ivan Cervantes


You could write your own by looking at the JPEG format.

That said, try a pre-existing library like CImg, or Boost's GIL. Or for strictly JPEG's, libjpeg. There is also the CxImage class on CodeProject.

Here's a big list.

like image 28
GManNickG Avatar answered Sep 20 '22 16:09

GManNickG