【问题标题】:Read and convert Monochrome bitmap file into CByteArray MFC读取单色位图文件并将其转换为 CByteArray MFC
【发布时间】:2014-02-09 07:57:09
【问题描述】:

在我的 MFC 项目中,我需要读取单色位图文件并将其转换为 CByteArray。使用“CFile”类以“Read”模式读取位图文件时,似乎它提供的长度比原来的长。

我的 MFC 代码:-

CFile ImgFile;
CFileException FileExcep;
CByteArray* pBinaryImage = NULL;
strFilePath.Format("%s", "D:\\Test\\Graphics0.bmp");

if(!ImgFile.Open((LPCTSTR)strFilePath,CFile::modeReadWrite,&FileExcep))
{
    return NULL;
}   
pBinaryImage = new CByteArray();
pBinaryImage->SetSize(ImgFile.GetLength());

// get the byte array's underlying buffer pointer
LPVOID lpvDest = pBinaryImage->GetData();

// perform a massive copy from the file to byte array
if(lpvDest)
{
    ImgFile.Read(lpvDest,pBinaryImage->GetSize());
}
    ImgFile.Close();

注意:文件长度设置为 bytearray obj。

我用 C# 检查了以下示例:-

        Bitmap bmpImage = (Bitmap)Bitmap.FromFile("D:\\Test\\Graphics0.bmp");
        ImageConverter ic = new ImageConverter();
        byte[] ImgByteArray = (byte[])ic.ConvertTo(bmpImage, typeof(byte[]));

在比较“pBinaryImage”和“ImgByteArray”的大小时,它不一样,我猜“ImgByteArray”的大小是正确的,因为从这个数组值,我可以得到我原来的位图。

【问题讨论】:

  • 您的 C# 示例解析位图标头,只为您提供像素。您的 MFC 示例读取整个位图,包括标题,您不知道像素数据在哪里。阅读前需要了解位图文件格式。
  • @RogerRowland:感谢您的评论。我已经用我的其他位图检查了两个字节数组的大小。大多数时候,两者都是一样的。对于少数位图,它们不是。然后只有我怀疑要阅读的大小。如果您给出解决方案,这对我会有帮助。

标签: visual-c++ image-processing bitmap bytearray cfile


【解决方案1】:

正如我在 cmets 中所指出的,通过使用 CFile 读取整个文件,您也在读取位图标题,这将破坏您的数据。

这是一个示例函数,展示了如何从文件加载单色位图,将其包装在 MFC 的 CBitmap 对象中,查询尺寸等并将像素数据读入数组:

void LoadMonoBmp(LPCTSTR szFilename)
{
    // load bitmap from file
    HBITMAP hBmp = (HBITMAP)LoadImage(NULL, szFilename, IMAGE_BITMAP, 0, 0,
                                          LR_LOADFROMFILE | LR_MONOCHROME);

    // wrap in a CBitmap for convenience
    CBitmap *pBmp = CBitmap::FromHandle(hBmp);

    // get dimensions etc.
    BITMAP pBitMap;
    pBmp->GetBitmap(&pBitMap);

    // allocate a buffer for the pixel data
    unsigned int uBufferSize = pBitMap.bmWidthBytes * pBitMap.bmHeight;
    unsigned char *pPixels = new unsigned char[uBufferSize];

    // load the pixel data
    pBmp->GetBitmapBits(uBufferSize, pPixels);

    // ... do something with the data ....

    // release pixel data
    delete [] pPixels;
    pPixels = NULL;

    // free the bmp
    DeleteObject(hBmp);
}

BITMAP 结构将为您提供有关位图 (MSDN here) 的信息,对于单色位图,这些位将被打包到您读取的字节中。这可能是与 C# 代码的另一个区别,其中每个位都可能被解压缩成一个完整的字节。在 MFC 版本中,您需要正确解释此数据。

【讨论】:

    猜你喜欢
    • 2014-09-16
    • 1970-01-01
    • 2016-03-11
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多