Question
Convert a string to an Image
Solution
bool ConvertCharToBitmap(TCHAR* szFileName, TCHAR* szStr, int iWidth, int iHeight, int iFontSize)
{
HDC hDC = GetDC(hWnd);
HDC hMemDC = CreateCompatibleDC(hDC);
SetTextColor(hMemDC, RGB(0, 255, 255));
SetBkMode(hMemDC, TRANSPARENT);
HBITMAP hBitmap = CreateCompatibleBitmap(hDC, iWidth, iHeight);
HBITMAP hOldBitmap = (HBITMAP)SelectObject(hMemDC, hBitmap);
HFONT hFont = CreateFont(300, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_OUTLINE_PRECIS,
CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, VARIABLE_PITCH, TEXT("Impact"));
HFONT hOldFont = (HFONT)SelectObject(hMemDC, hFont);
HBRUSH hBrush = CreateSolidBrush(RGB(255, 255, 0));
HBRUSH hOldBrush = (HBRUSH)SelectObject(hMemDC, hBrush);
RECT rc = { 0, 0, iWidth, iHeight };
FillRect(hMemDC, &rc, hBrush);
DrawText(hMemDC, szStr, -1, &rc, DT_CENTER | DT_SINGLELINE | DT_VCENTER);
TextOut(hMemDC, 0, 0, szStr, -1);
BITMAP bmp;
GetObject(hBitmap, sizeof(BITMAP), &bmp);
BITMAPFILEHEADER bmfHeader;
BITMAPINFOHEADER bi;
bi.biSize = sizeof(BITMAPINFOHEADER);
bi.biWidth = bmp.bmWidth;
bi.biHeight = bmp.bmHeight;
bi.biPlanes = 1;
bi.biBitCount = 32;
bi.biCompression = BI_RGB;
bi.biSizeImage = 0;
bi.biXPelsPerMeter = 0;
bi.biYPelsPerMeter = 0;
bi.biClrUsed = 0;
bi.biClrImportant = 0;
DWORD dwBmpSize = ((bmp.bmWidth * bi.biBitCount + 31) / 32) * 4 * bmp.bmHeight;
HANDLE hDIB = GlobalAlloc(GHND, dwBmpSize);
char *lpBitmap = (char *)GlobalLock(hDIB);
// Gets the "bits" from the bitmap and copies them into a buffer
// which is pointed to by lpbitmap.
GetDIBits(hMemDC, hBitmap, 0,
(UINT)bmp.bmHeight,
lpBitmap,
(BITMAPINFO *)&bi, DIB_RGB_COLORS);
// A file is created, this is where we will save the screen capture.
HANDLE hFile = CreateFile(szFileName,
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
// Add the size of the headers to the size of the bitmap to get the total file size
DWORD dwSizeofDIB = dwBmpSize + sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER);
//Offset to where the actual bitmap bits start.
bmfHeader.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER)+(DWORD)sizeof(BITMAPINFOHEADER);
//Size of the file
bmfHeader.bfSize = dwSizeofDIB;
//bfType must always be BM for Bitmaps
bmfHeader.bfType = 0x4D42; //BM
DWORD dwBytesWritten = 0;
WriteFile(hFile, (LPSTR)&bmfHeader, sizeof(BITMAPFILEHEADER), &dwBytesWritten, NULL);
WriteFile(hFile, (LPSTR)&bi, sizeof(BITMAPINFOHEADER), &dwBytesWritten, NULL);
WriteFile(hFile, (LPSTR)lpBitmap, dwBmpSize, &dwBytesWritten, NULL);
//Unlock and Free the DIB from the heap
GlobalUnlock(hDIB);
GlobalFree(hDIB);
//Close the handle for the file that was created
CloseHandle(hFile);
//SelectObject(hMemDC, hOldBrush);
SelectObject(hDC, hOldFont);
SelectObject(hDC, hOldBitmap);
//DeleteObject(hBrush);
DeleteObject(hFont);
DeleteObject(hBitmap);
DeleteDC(hMemDC);
ReleaseDC(NULL, hDC);
return true;
}
Output