c++ - Bitblt,createdibsection,图像损坏

标签 c++ bitblt createdibsection

您好我试图捕获屏幕截图,但图像出来损坏,任何人都可以看到代码有什么问题,基本上我试图使用createdibsection以便我可以直接访问这些位。

这就是结果图片
http://oi47.tinypic.com/33c4zko.jpg

bool FrameData::Create(int width, int height, ImageFormat imgFormat, HWND sourceWindow)
{
if(width < 0)
    return false;

srcWndDC = GetDC(sourceWindow);
hdc = CreateCompatibleDC(srcWndDC);

if(hdc == nullptr || srcWndDC == nullptr)
{
    return false;
}

memset(&bmpInfo, 0, sizeof(BITMAPINFO));
bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmpInfo.bmiHeader.biWidth = width;
bmpInfo.bmiHeader.biHeight = -height; // top-down
bmpInfo.bmiHeader.biPlanes = 1;
switch(imgFormat)
{
case ImageFormat::RGB16:
        bmpInfo.bmiHeader.biBitCount = 16;
        break;
    case ImageFormat::RGB24:
        bmpInfo.bmiHeader.biBitCount = 24;
        break;
    case ImageFormat::RGB32:
        bmpInfo.bmiHeader.biBitCount = 32;
        break;
    default:
        return false;

}
bmpInfo.bmiHeader.biCompression = BI_RGB;
bmpInfo.bmiHeader.biSizeImage = height * width * imgFormat;
hBitmap = CreateDIBSection(srcWndDC, &bmpInfo, DIB_RGB_COLORS, (void**)&bits, NULL, NULL);

if(hBitmap == nullptr)
{
    return false;
}

return true;


}

bool FrameData::SaveFrameToFile(std::string& filename)
{
BITMAPFILEHEADER bmpFileHdr = {0};

bmpFileHdr.bfSize=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+bmpInfo.bmiHeader.biSizeImage;
bmpFileHdr.bfType='MB';
bmpFileHdr.bfOffBits=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER);

std::ofstream outfile;
outfile.open(filename);

if(!outfile.is_open())
{
    return false;
}


outfile.write((char*)&bmpFileHdr, sizeof(BITMAPFILEHEADER));
outfile.write((char*)&bmpInfo.bmiHeader, sizeof(BITMAPINFOHEADER));
outfile.write((char*)bits, bmpInfo.bmiHeader.biSizeImage);
outfile.close();
return true;
}

多数民众赞成在代码,然后我只是用它来捕获屏幕
 SelectObject(data.GetHDC(), data.GetHBitmap());
 BitBlt(data.GetHDC(),0,0,data.GetWidth(), data.GetHeight(),           data.GetSourceWindowDC(),0,0 , SRCCOPY | CAPTUREBLT);

最佳答案

没有时间检查位图结构初始化的所有详细信息,而是尝试outfile.open(filename, ios_base::out + ios_base::bin);而不是outfile.open(filename);,否则所有0x0A字节('\ n'或LineFeed)将被0x0D('\ r'或CarriageReturn)替换为0x0A (2字节MS-DOS / Windows文本文件行尾序列)!

我也认为bmpInfo.bmiHeader.biSizeImage应该类似于height * 4 * (((width * bmpInfo.bmiHeader.biBitCount) + 0x1F) / 0x20)(每行像素必须是32位对齐的,导致每行末尾最多3个未使用的填充字节,对于RGB32格式无关紧要)。

关于c++ - Bitblt,createdibsection,图像损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11483249/

相关文章:

c++ - 在 C++ 中从 HBITMAP 转换为 Jpeg 或 Png

c - 来自 directx 应用程序的 Bitblt

c++ - 16 位桌面颜色深度的 BitBlt + UpdateLayeredWindow 和 CreateDIBSection

c# - 将图形内容复制到位图

c++ - 如何将像素数组转换为 HBITMAP

winapi - 了解 GetDiBits。 C++

c++ - 在这种情况下, volatile 限定词重要吗?

c++ - 使用 system() 执行 ssh 命令

c++ - 将 OpenGL 代码从 C++ 移植到 Python

c++ - 将文本附加到空间不足的编辑控件?