Reputation: 4903
Question is rather simple but I couldn't find nice & clean solution to my problem on the Internet. What I got are some drawings on my window. Now, I can save those using BitBlt function from window device context to image device context, and also from there to bitmap handle:
HDC bitmapDC = CreateCompatibleDC(dc);
HBITMAP bitmap = CreateCompatibleBitmap(bitmapDC, 200, 200);
SelectObject(bitmapDC,bitmap);
BitBlt(bitmapDC, 0, 0, 200, 200, dc, 200, 200, SRCCOPY);
But from there I'm lost. I had a look at GDI+ Bitmap class which got save function, and I found how to implement code for retrieving CLSID of picture encoding. However I don't know if I use loading to that class correctly. There's overloaded constructor for HBITMAP, but it's also asking for some palette, which I set to NULL:
Bitmap image(bitmap,NULL);
I tried to save png file but it resulted in black quare without those drawings I was expecting. If you'd like, full code for my painting procedure:
void GetCLSID(const WCHAR* format, CLSID* pClsid){
UINT num = 0; // number of image encoders
UINT size = 0; // size of the image encoder array in bytes
ImageCodecInfo* pImageCodecInfo = NULL;
GetImageEncodersSize(&num, &size);
pImageCodecInfo = (ImageCodecInfo*)(malloc(size));
GetImageEncoders(num, size, pImageCodecInfo);
for(UINT j = 0; j < num; ++j)
{
if( wcscmp(pImageCodecInfo[j].MimeType, format) == 0 )
{
*pClsid = pImageCodecInfo[j].Clsid;
free(pImageCodecInfo);
}
}
}
void OnPaint(HDC dc){
RECT rect; rect.bottom = 0; rect.top = 20; rect.left = 0; rect.right = 100;
HBRUSH blueBrush = CreateSolidBrush(RGB(0,0,200));
FillRect(dc, &rect, blueBrush);
Graphics graphics(dc);
Pen pen(Color(255, 0, 0, 255));
graphics.DrawLine(&pen, 0, 0, 200, 100);
SolidBrush greenBrush(Color(0,200,0));
Rect ellipseRect(20,20,20,20);
graphics.FillEllipse(&greenBrush, ellipseRect);
SolidBrush redBrush(Color(200,0,0));
Rect boxRectangle(0,40,20,100);
graphics.FillRectangle(&redBrush, boxRectangle);
pen.SetColor(Color(200,0,200));
pen.SetWidth(20);
graphics.DrawBezier(&pen, 100, 20, 130, 40, 200, 10, 230, 20);
HDC bitmapDC = CreateCompatibleDC(dc);
HBITMAP bitmap = CreateCompatibleBitmap(bitmapDC, 200, 200);
SelectObject(bitmapDC,bitmap);
BitBlt(bitmapDC, 0, 0, 500, 500, dc, 500, 500, SRCCOPY);
Bitmap image(bitmap,NULL);
CLSID clsID;
GetCLSID(L"image/png", &clsID);
image.Save(L"pic.png", &clsID);
}
I couldn't even imagine that simple saving will be such problem, so I'll be glad for any help, thanks!
Upvotes: 0
Views: 11015
Reputation: 24477
I gave code here which does pretty much what you want: How to save the client area of a child Window to a Bitmap file?
It is very verbose in C. It's a lot better in C++ because of CImage
Upvotes: 2