Replace Pixels from a bmp into another bmp file.

Hey i have to copy the pixels from this bmp¹ file ( https://imgur.com/la1frjx ) into this bmp² file ( https://imgur.com/iwNqkfG ).
I got it to read the header of the two bmp files. But know i have no idea how i schould copy the pixels from bmp¹ into bmp². Only using the givin libarys.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <stdio.h>
#include "windows.h"

int main()
{
    int i;
    FILE* Pic1 = fopen("pic1.bmp", "rb");
    FILE* Pic2 = fopen("pic2.bmp", "rb+");
    unsigned char infoPic1[54];
    fread(infoPic1, sizeof(unsigned char), 54, Pic1); // read the 54-byte header from Pic1

    // extract image height and width from Pic1
    int widthPic1 = *(int*)&infoPic1[18];
    int heightPic1 = *(int*)&infoPic1[22];

    int sizePic1 = 3 * widthPic1 * heightPic1;

    unsigned char infoPic2[54];
    fread(infoPic2, sizeof(unsigned char), 54, Pic2); // read the 54-byte header from Pic2

    // extract image height and width from Pic2
    int widthPic2 = *(int*)&infoPic2[18];
    int heightPic2 = *(int*)&infoPic2[22];

    int sizePic2 = 3 * widthPic2 * heightPic2;

    printf("Pic1 is %i*%i pixels and %ibyte\nPic2 is %i*%i and %ibytes\n\n", heightPic1, widthPic1, sizePic1, heightPic2, widthPic2, sizePic2);

    system("PAUSE");
    return 0;
}
Last edited on
What are "the givin libarys"?

How much are you willing to write yourself, and how much are you willing to rely on other library code.
Since you're on windows, maybe this is somewhere to start.
https://docs.microsoft.com/en-us/windows/win32/gdi/bitmaps

https://en.wikipedia.org/wiki/BMP_file_format
> fread(infoPic1, sizeof(unsigned char), 54, Pic1);
Well the first thing you should do is read only up to "DIB header size" to figure out how big the header really is, rather than just assume all bitmaps are the same.

> int widthPic1 = *(int*)&infoPic1[18];
This isn't portable.
Sure, it probably does what you want on your wintel machine.

But at some point, each of these is likely to bite you.
https://en.wikipedia.org/wiki/Data_structure_alignment
https://en.wikipedia.org/wiki/Endianness
https://en.wikipedia.org/wiki/Bus_error

1
2
3
4
5
6
7
8
int readIntFromBytes(unsigned char *b) {
  int result = b[0] | (b[1]<<8) | (b[2] << 16) | (b[3] << 24);
  return result;
}

///

int widthPic1 = readIntFromBytes(&infoPic1[18]);


> int sizePic2 = 3 * widthPic2 * heightPic2;
Again, you're assuming a particular kind of bitmap.

As a first exercise, a program to just print all the members of the BITMAPVxHEADER would be a good start, as it would give you some measure of confidence that you could go on to decode the rest of the file successfully.
http://easybmp.sourceforge.net/

Unless the whole point is to learn how to read and write .bmp files, don't waste your time doing it yourself.
Topic archived. No new replies allowed.