【发布时间】:2021-11-06 00:58:32
【问题描述】:
我正在尝试将hdc 的内容保存到位图文件中,我目前正在使用上面的代码,它确实保存了图像,但我无法打开它。
看起来它已损坏,并且始终具有相同的大小(54 字节)。
我可能在 HDCTofile 函数中做错了。
#include <vector> // HDCToFile
#include <fstream>
#include <cstring>
#include <windows.h>
HDCToFile("output.bmp", hdc);
bool HDCToFile(const char* FilePath, HDC Context, uint16_t BitsPerPixel = 24)
{
//uint32_t Width = Area.right - Area.left;
//uint32_t Height = Area.bottom - Area.top;
BITMAPINFO Info;
BITMAPFILEHEADER Header;
memset(&Info, 0, sizeof(Info));
memset(&Header, 0, sizeof(Header));
Info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
//Info.bmiHeader.biWidth = Width;
//Info.bmiHeader.biHeight = Height;
Info.bmiHeader.biPlanes = 1;
Info.bmiHeader.biBitCount = BitsPerPixel;
Info.bmiHeader.biCompression = BI_RGB;
//Info.bmiHeader.biSizeImage = Width * Height * (BitsPerPixel > 24 ? 4 : 3);
Header.bfType = 0x4D42;
Header.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
char* Pixels = NULL;
HDC MemDC = CreateCompatibleDC(Context);
HBITMAP Section = CreateDIBSection(Context, &Info, DIB_RGB_COLORS, (void**)&Pixels, 0, 0);
DeleteObject(SelectObject(MemDC, Section));
BitBlt(MemDC, 0, 0, Info.bmiHeader.biWidth, Info.bmiHeader.biHeight, Context, 0, 0, SRCCOPY);
DeleteDC(MemDC);
std::fstream hFile(FilePath, std::ios::out | std::ios::binary);
if (hFile.is_open())
{
hFile.write((char*)&Header, sizeof(Header));
hFile.write((char*)&Info.bmiHeader, sizeof(Info.bmiHeader));
hFile.write(Pixels, (((BitsPerPixel * Info.bmiHeader.biWidth + 31) & ~31) / 8) * Info.bmiHeader.biHeight);
hFile.close();
DeleteObject(Section);
return true;
}
DeleteObject(Section);
return false;
}
【问题讨论】:
-
评论
Info结构体的heigh和width有一些原因? -
如果我取消注释所有内容,您的代码将有效。显示你是如何打电话给
HDCToFile