1

I have a 2D array of size 320x240 which contains values ranging from 0 to 255. I want to store this data as a grayscale image.

This is the code I have written so far:

int val[320][240];
FILE *image = fopen("depth.png","wb");
for (i=0; i < 320; i++)
{
    for (j=0; j<240; j++)
{
    printf("\nWriting to pixel %d %d in image",i,j);
    fwrite(&val[i][j], sizeof(int), sizeof(int),image);
}
}

fclose(image);

However this code does not produce a proper image. Please provide suggestions for correcting the code.

  • 1
    You can't just write raw values to a file and expect the result to be a proper image. You need to write a file according to the file format. What kind of image file do you want? – Reticulated Spline Feb 20 '15 at 22:20
  • Look up the header for a bitmap, and just plop that puppy before your binary data and it should work. – BWG Feb 20 '15 at 22:22
  • 1
    png files are quite complex. What you're writing is just raw data. – Retired Ninja Feb 20 '15 at 22:23
  • 1
    If you're really serious about this, I'd look at [BMP](http://en.wikipedia.org/wiki/BMP_file_format) or [PGM](http://en.wikipedia.org/wiki/Netpbm_format). PNG will be far too complex. – Mark Ransom Feb 20 '15 at 22:38
  • Check out [this post](http://www.cplusplus.com/forum/beginner/4307/#msg19006) which describes the format of the BMP file, as well as [this](http://stackoverflow.com/questions/2654480/writing-bmp-image-in-pure-c-c-without-other-libraries). BMP seems to be the easiest format to write without the use of a library. Otherwise, [here is a post](http://stackoverflow.com/a/11817422/2544158) that discusses different libraries you can use. – Reticulated Spline Feb 21 '15 at 01:57
  • I am okay with using any image format. I will try out BMP. How do I traverse each pixel in the image properly so that I can write the required value for each of them? – Gaurav Yengera Feb 21 '15 at 11:14
  • BMP has some oddities of its own. Start with [pgm](http://netpbm.sourceforge.net/doc/pgm.html). – Jongware Feb 21 '15 at 23:41

2 Answers2

0

You have other issues to worry about -- like the format of the image file. However, what you are attempting with the following line is wrong:

fwrite(&val[i][j], sizeof(int), sizeof(int), image);

If sizeof(int) is 4, it will write 4 x 4 bytes. What you need to write one integer is:

fwrite(&val[i][j], sizeof(int), 1, image);

Not only that, you'll also end up accessing the array out of bounds, which will lead to undefined behavior.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

Since your array contains raw image data you need to write it in raw format e.g. yuv 4:0:0. Your precision is uint8,(0 255), you need to write each pixel by unsigned char precision.

unsigned char val[320][240];
FILE *image = fopen("depth.yuv", "wb");
for (unsigned int i = 0; i < 320; i++)
{
    for (unsigned int j = 0; j< 240; j++)
    {
        fwrite(&val[i][j], sizeof(unsigned char), 1, image);
    }
}

fclose(image);