我在VC ++ 6中使用位图有一个项目。我想以编程方式提取几个位图并保存为.bmp文件。
请给我一些建议。
这些是我想要做的几个步骤。
提前致谢 问候
ULKA
答案 0 :(得分:4)
可执行文件中的位图资源只是剥离了BITMAPFILEHEADER的位图文件。 另见:https://blogs.msdn.microsoft.com/oldnewthing/20091211-00/?p=15693
所以你需要做的就是自己创建这个标题并首先将其写入文件。对于最常见的24 bpp位图来说相对容易,但如果你想支持其他位深度则需要更多一些。
接下来写下通过FindResource()/ LoadResource()/ LockResource()调用获得的数据。
代码示例(使用1 bpp,4 bpp,8 bpp和24 bpp位图测试):
int main()
{
// Obtain a handle to the current executable
HMODULE hInst = ::GetModuleHandle( nullptr );
// Locate and load a bitmap resource of the executable
if( HRSRC hr = ::FindResource( hInst, MAKEINTRESOURCE( IDB_BITMAP1 ), RT_BITMAP ) )
if( HGLOBAL hg = ::LoadResource( hInst, hr ) )
if( auto pData = reinterpret_cast<const char*>( ::LockResource( hg ) ) )
{
DWORD resourceSize = ::SizeofResource( hInst, hr );
// Check if we safely read the complete BITMAPINFOHEADER
// (to prevent a GPF in case the resource data is corrupt).
if( resourceSize >= sizeof( BITMAPINFOHEADER ) )
{
auto& bmih = reinterpret_cast<const BITMAPINFOHEADER&>( *pData );
// For simplicitly we can only save uncompressed bitmaps.
if( bmih.biCompression == BI_RGB )
{
// Calculate the size of the bitmap pixels in bytes.
// We use this to calculate BITMAPFILEHEADER::bfOffBits correctly.
// This is much easier than calculating the size of the color table.
DWORD widthBytes = ( bmih.biBitCount * bmih.biWidth + 31 ) / 32 * 4;
DWORD heightAbs = abs( bmih.biHeight ); // height can be negative for a top-down bitmap!
DWORD pixelSizeBytes = widthBytes * heightAbs;
// Create the bitmap file header.
BITMAPFILEHEADER bfh = { 0 };
bfh.bfType = 0x4D42; // magic bytes: "BM"
bfh.bfSize = sizeof( bfh ) + resourceSize; // total file size
bfh.bfOffBits = bfh.bfSize - pixelSizeBytes; // offset to bitmap pixels
// Write file header and bitmap resource data to file.
std::ofstream of( "mybitmap1.bmp", std::ios::binary );
of.write( reinterpret_cast<const char*>( &bfh ), sizeof( bfh ) );
of.write( pData, resourceSize );
}
}
}
return 0;
}
修改:
我的原始答案错过了一个关键位(字面意思),即ofstream构造函数的ios::binary
标志。这就是为什么代码不适用于Arthur G.
那为什么即使没有国旗,它实际上对我有用?有趣的是它只能工作,因为我的测试位图没有任何值为10的字节(从不相信程序员测试自己的代码)!
默认情况下可能发生的一件事是线路结尾将根据平台默认值进行转换。也就是说,'\ n'(ASCII码= 10)将在Windows平台上转换为“\ r \ n”。当然,这将完全弄乱位图数据,因为任何真正的位图很可能在某处包含此值。
所以我们必须明确告诉ofstream我们的数据不应该被搞乱,这正是ios :: binary标志所做的。
编辑2:
为了好玩,我扩展了我的示例,以便正确地处理1位,4位和8位每像素位图。
这涉及更多一点,因为对于这些位深度,像素阵列不会在BITMAPINFOHEADER之后立即启动。在像素阵列出现之前,颜色表的大小必须添加到BITMAPFILEHEADER::bfOffBits
。
根据MSDN,问题更复杂,因为即使位深度为16或更大,也可以有一个可选的颜色表(“以优化系统调色板的性能” - 无论这意味着什么)! 见https://msdn.microsoft.com/en-us/library/windows/desktop/dd183376(v=vs.85).aspx(在“biClrUsed”下)
因此,我不是围绕使用颜色表的时间和方式的所有脏细节包围我,而是通过从总资源大小中减去像素数组的大小来计算BITMAPFILEHEADER::bfOffBits
(已经是已知的)。
计算像素数组的大小非常简单,但必须注意以字节为单位的宽度向上舍入到下一个4的倍数(一个DWORD)。否则,在保存以字节为单位的宽度不是4的倍数的位图时,您将收到错误。
奖金阅读
维基百科对位图文件格式进行了深入的描述,并提供了一个很好的结构图: https://en.wikipedia.org/wiki/BMP_file_format