I have some old C++/MFC code which uses GDI to create an image in a device context (CDC
), using functions like Rectangle
. The image is then painted to the screen, by the destructor of CPaintDC
. Everything works as expected.
Now I want to store the image in a PNG file. For this, I am using Windows Imaging Component (WIC). I can create an image in WIC by creating a bitmap frame, storing pixels in a buffer, and copying the pixels into it using WritePixels
. Then WIC stores the image as a PNG file via Commit
. All this also works.
The question is, how can I transfer the image I created using GDI, which is in a CDC
, to something WIC recognizes? I'm looking for something more efficient than a CDC::GetPixel
loop storing into a buffer followed by WritePixels
.
Windows 7, Visual Studio 2015, C++.
Update: I'm trying to get the CImage method suggested by @Andrew Komiagin. My code is
CDC memdc;
memdc.CreateCompatibleDC(nullptr);
myControl.RenderToDC(memdc); // this draws the image onto the dc
CBitmap bmp;
BOOL ok=bmp.CreateCompatibleBitmap(&memdc, w, h); // w=h=292 defined elsewhere
CBitmap *pOldBitmap=memdc.SelectObject(&bmp);
ok=memdc.BitBlt(0, 0, w, h, &memdc, 0, 0, SRCCOPY);
CImage tempImageObj;
tempImageObj.Attach((HBITMAP)bmp.Detach());
CString outputFilename("outputImage.png");
HRESULT hr=tempImageObj.Save(outputFilename);
This produces a PNG image file with an all-black square, w x h pixels, rather than the image I drew. I know the image is being drawn correctly by RenderToDC
(see below).
For comparison, this is in MyControl::OnPaint
for the control (derived from CStatic
):
CPaintDC dc(this); // device context for painting
RenderToDC(dc); // this draws the image onto the dc
// Painted to screen by CPaintDC's destructor
The image appears correctly.