#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <process.h>
#include <string.h>
#include <math.h>

int count = 0;

typedef struct bitmap24 {
    unsigned char header[54];
    unsigned char* pixels;

void readBMP (char* filename) {
    int i;
    FILE* f  = fopen(filename, "rb");
    FILE* f1 = fopen("save.bmp", "wb");
    FILE* pixelVals = fopen("vals.dat", "w");
    unsigned char bmppad[3] = {0, 0, 0};
    if (!f) {
        printf("Could not read file!\n");
    unsigned char info[54];
    fread(info, sizeof(unsigned char), 54, f);
    int width  = *(int*)&info[18];
    int height = *(int*)&info[22];

    unsigned char *img = NULL;
    if (img)
    img = (unsigned char*)malloc(3*width*height);
    memset(img, 0, sizeof(img));

    fwrite(info, sizeof(unsigned char), 54, f1);

    int length = width * height;
    unsigned long int image[10000][3];

    for(i = 0; i < length; i++) {
        image[i][2] = getc(f); // blue
        image[i][1] = getc(f); // green
        image[i][0] = getc(f); // red

        img[count] = 255-(unsigned char)image[i][0];
        count += 1;
        img[count] = 255-(unsigned char)image[i][1];
        count += 1;
        img[count] = 255-(unsigned char)image[i][2];
        count += 1;

        printf("pixel %d : [%d,%d,%d]\n", i+1, image[i][0], image[i][1], image[i][2]);
        fprintf(pixelVals, "pixel %d : [%d,%d,%d]\n", i+1, image[i][0], image[i][1], image[i][2]);

    **for(i = 0; i < height; i++) {
        fwrite(img+(width*(height - i - 1)*3), 3, width, f1);
        fwrite(bmppad, 1, (4-(width * 3)%4)%4, f1);


void main() {
    char* fileName = "bitgray.bmp";

This is a code that saves the negative of a 24-bit BMP.
The original and the negative image can be downloaded from those links.
Negative Image
Original Image

The final image that is saved is slanting and inverted. I feel that there is something wrong in the last for loop. Could you please help in solving this issue ?

I can't tell by looking at your code, what's wrong. My suggestion is you alter your code temporarily, and have it put out EXACTLY the same pic.

Now you can use utilities like "fc /b filename filename" (but check it with "fc /?", because I haven't used it in a long time), to do a binary comparison of the files and see where the differences are - and thus find your error. (Linux has similar tools).

Looking at an altered image, it's very hard to see the exact pixels that are wrong. Looking at two versions of the SAME image, when magnified with something like Windows Paint, or any image editing program, it because a LOT easier.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.