Bitblt,createdibsection,图像出现损坏

时间:2012-07-14 11:06:14

标签: 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);

1 个答案:

答案 0 :(得分:1)

没有时间检查位图结构初始化的所有细节,但尝试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格式而言。)