0

With the code sample below, I have successfully created a .bmp file which when opened simply displays a grey square. Now I would like to add text to the bitmap before saving it. For example: "Hello World" in green should be displayed on top of the grey square. The stackoverflow post here is the closest thing i've found so far. Unfortunately I still can't figure out the full implementation.

Please note that I would like to avoid the use of any third party libraries. Any help will be appreciated, Thanks.

void SaveImage(const char* filename)
{
    int Width = 470;
    int Height = 470;
    FILE *f;
    unsigned char *img = NULL;
    int triple_area = 3*Width*Height;
    if(img) free(img);
    img = (unsigned char *)malloc(triple_area);
    memset(img,0,sizeof(img));
    int res;
    Assign_Bitmap_Req(triple_area); //Sets up BmpFileHeader, BmpInfoHeader, BmpPadding as unsigned char arrays

    for(int i=0; i<Width; i++)
    {
        for(int j=0; j<Height; j++)
        {
            res = Height - 1 - j;
            img[(i+res*Width)*3+2] = (unsigned char)(100);
            img[(i+res*Width)*3+1] = (unsigned char)(100);
            img[(i+res*Width)*3+0] = (unsigned char)(100);
        }
    }

    f = fopen(filename,"wb");
    fwrite(BmpFileHeader,1,14,f);
    fwrite(BmpInfoHeader,1,40,f);
    int remainder = (4-(Width*3)%4)%4;
    for(int i=0; i<Height; i++)
    {
        fwrite(img+(Width*(Height-i-1)*3),3,Width,f);
        fwrite(BmpPadding,1,remainder,f);
    }
    fclose(f);
}
Community
  • 1
  • 1
BeeLabeille
  • 174
  • 1
  • 4
  • 16
  • 3
    The easiest way (since you've tagged for winapi) is to create a DIB section, and use GDI to render the text before writing the bits to the file. – Jonathan Potter Nov 03 '15 at 12:29
  • @JonathanPotter when you say "create a DIB section" i guess you mean something like this `void *ppvBits = NULL; HBITMAP bmpHandle = CreateDIBSection(GetDC(0), (BITMAPINFO *)&BmpInfoHeader, DIB_RGB_COLORS, &ppvBits, NULL, 0);`? I'm not sure about the second part of your comment though. Is GDI a library that i need to download in order to render the text? Also is it compatible with the HBITMAP returned from CreateDIBSection? – BeeLabeille Nov 03 '15 at 14:22
  • You've tagged the question WinAPI. GDI is part of the WinAPI. – Ben Nov 03 '15 at 14:54
  • @Ben oh okay thanks. I'd never heard of GDI before. I'll look it up on the msdn website. – BeeLabeille Nov 03 '15 at 15:32

0 Answers0