Pages

Sunday, October 11, 2009

Конвертировать Image из GDI+ в примитивный HBITMAP

Фунция Load загрузит BMP/PNG/JPG файл и конвертирует его в 32-битную DIBSection:
#include <Windows.h>
#include <atlbase.h>
#include <gdiplus.h>
#pragma comment(lib, "gdiplus.lib")
using namespace Gdiplus;


BOOL Load(LPCWSTR lpszFile, HBITMAP* phBitmap)
{
if (lpszFile == NULL || phBitmap == NULL)
return FALSE;

ULONG_PTR gdiplusToken;
GdiplusStartupInput gdiplusStartupInput;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

Image* pImage = Image::FromFile(lpszFile, FALSE);

UINT nWidth = pImage->GetWidth();
UINT nHeight = pImage->GetHeight();

if (nWidth > 0 && nHeight > 0)
{
BITMAPINFO bmi = { 0 };
LPBYTE pBits = NULL;

bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = nWidth;
bmi.bmiHeader.biHeight = nHeight;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;

HDC hWndDC = GetDC(NULL);
HDC hDC = CreateCompatibleDC(hWndDC);
HBITMAP hBitmap = ::CreateDIBSection(hWndDC, &bmi,
DIB_RGB_COLORS, (void**)&pBits, NULL, 0);

if (hBitmap != NULL)
{
HGDIOBJ hOld = SelectObject(hDC, hBitmap);
Graphics graphics(hDC);
graphics.DrawImage(pImage,
0, 0, nWidth, nHeight);
SelectObject(hDC, hOld);
*phBitmap = hBitmap;
}

DeleteDC(hDC);
ReleaseDC(NULL, hWndDC);
}

GdiplusShutdown(gdiplusToken);
return TRUE;
}

No comments:

Post a Comment