• Advertisement
Sign in to follow this  

Using GDI functions and saving them as a bitmap

This topic is 4340 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I want to be able to use GDI functions to make graphics and save it to a bitmap file. However, the bitmap can be much larger than the screen, so I don't think I can just do it on a screen DC and then copy it to a bitmap. The following code is a test to see how to write something to a bitmap. I try to do a square in the top left of the bitmap. There is a square written in the correct-ish area, but it is just a mix of black and white pixels. I am using the bitsperpixel of the DC, which isn't monochrome. Also, the area of the bitmap where the rectangle isn't is solid black. Here is the code:
int Width = 640*Screens;
int Height = 480;

HDC hScreenDC = GetWindowDC(0);
HDC BmpHDC = CreateCompatibleDC(hScreenDC);
HBITMAP hmemBM = CreateCompatibleBitmap(BmpHDC, Width, Height);
HBRUSH hBrush = CreateSolidBrush(RGB(195,55,87));
SelectObject(BmpHDC,hBrush);
SelectObject(BmpHDC,hmemBM);

//Polyline(BmpHDC,pt,640*Screens);
Rectangle(BmpHDC,1,1,101,101);

int BytesPerPixel = (int)GetDeviceCaps(BmpHDC,BITSPIXEL);

HGLOBAL hpxldata = GlobalAlloc(GMEM_FIXED, Width*Height*BytesPerPixel);
void FAR* lpvpxldata = GlobalLock(hpxldata);

BITMAPINFO bmInfo;
bmInfo.bmiHeader.biSize = 40;
bmInfo.bmiHeader.biWidth = Width;
bmInfo.bmiHeader.biHeight = Height;
bmInfo.bmiHeader.biPlanes = 1;
bmInfo.bmiHeader.biBitCount = BytesPerPixel;//24
bmInfo.bmiHeader.biCompression = 0;
bmInfo.bmiHeader.biSizeImage = 0;
bmInfo.bmiHeader.biXPelsPerMeter = 0;
bmInfo.bmiHeader.biYPelsPerMeter = 0;
bmInfo.bmiHeader.biClrUsed = 0;
bmInfo.bmiHeader.biClrImportant = 0;

BITMAPFILEHEADER bmFileHeader;
bmFileHeader.bfType = 19778;
bmFileHeader.bfSize = (Width*Height*BytesPerPixel) + 40 + 14;
bmFileHeader.bfReserved1 = 0;
bmFileHeader.bfReserved2 = 0;
bmFileHeader.bfOffBits = 54;

GetDIBits(BmpHDC, hmemBM, 0, Height, lpvpxldata, &bmInfo, DIB_RGB_COLORS);

FILE *fp = fopen("Bitmap.bmp","wb");
fwrite(&bmFileHeader,1,14,fp);
fwrite(&bmInfo,1,40,fp);
fwrite(lpvpxldata,1,Width*Height*BytesPerPixel,fp);
fclose(fp);

GlobalUnlock(hpxldata);
GlobalFree(hpxldata);
DeleteObject(hmemBM);
DeleteObject(hBrush);
DeleteDC(BmpHDC);
ReleaseDC(0, hScreenDC);

Any ideas? Also, after looking around a bit, CreateDIBSection() might be a better alternative? I just have no clue how to implement it, there doesn't seem to be any good documentation. Thank you, Dev578

Share this post


Link to post
Share on other sites
Advertisement
Sign in to follow this  

  • Advertisement