Search code examples
cbmp8-bit

converting 24bpp bmp colour image to 8bpp grayscale bmp image in c


I am trying to convert 24bpp BMP color image to 8bpp grayscale BMP image. I have done something but i am not getting 100% correct output.

I have converted 24bpp to 8bpp. but in result image colour table is also being considered as pixel data. I have tried setting offset byte in header but problem still persists.

#include <stdio.h>

int main()
{

    FILE* fIn = fopen("lena_colored_256.bmp","rb");         
    FILE* fOut = fopen("lena_gray.bmp", "w+");              
    int i, j, y;
    unsigned char byte[54];
    unsigned char colorTable[1024];
    if (fIn == NULL)// check if the input file has not been opened
    {
        printf("File does not exist.\n");
    }

    for (i = 0; i < 54; i++)//read the 54 byte header from fIn
    {
        byte[i] = getc(fIn);

    }
    byte[28] = (unsigned char)8; // write code to modify bitDepth to 8

    byte[11] = (unsigned char)04;
    //write code to add colorTable

    for (i = 0; i < 256; i++)
    {
            colorTable[i * 4 + 0] = i;
            colorTable[i * 4 + 1] = i;
            colorTable[i * 4 + 2] = i;
            colorTable[i * 4 + 3] = i;
    }


    for (i = 0; i < 54; i++)
    {
        putc(byte[i], fOut);
    }
    for (i = 0; i < 1024; i++)
    {
        putc(colorTable[i], fOut);

    }
        // extract image height, width and bitDepth from imageHeader 
    int *height = (int)& byte[18];
    int *width = (int)& byte[22];
    int *bitDepth = (int)& byte[28];

    printf("bitDepth : %d\n", *bitDepth);
    printf("width: %d\n", *width);
    printf("height: %d\n", *height);
    int size = (*height) * (*width)*3; //calculate image size

    unsigned char* buffer;
    buffer = (unsigned char*)malloc(sizeof(int) * size);

    for (i = 0; i < size; i=i+3)    //RGB to gray
    {

        buffer[i+2] = getc(fIn);//blue
        buffer[i+1] = getc(fIn);//green
        buffer[i+0] = getc(fIn);//red

        y = (buffer[i+0] * 0.33) + (buffer[i+1] * 0.33) + (buffer[i+2] * 0.33);

        putc(y, fOut);
    }


    fclose(fOut);
    fclose(fIn);

    return 0;
}

Colour table data is also being considered as pixel data by image. i have checked my colour table data entering into BMP file. I have printed out file pointer location, after entering at 94th byte it is increasing by 2 byte instead of 1 byte, this is happening total 4 times and other 1020 time file pointer is increasing by 1 byte. Any explanation regarding this?


Solution

  • FILE* fOut = fopen("lena_gray.bmp", "w+");//ERROR
    FILE* fOut = fopen("lena_gray.bmp", "wb");//TRUE