1

在我的 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”的大小是正确的,因为从这个数组值,我可以得到我原来的位图。

4

1 回答 1

1

正如我在评论中指出的那样,通过使用 读取整个文件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),对于单色位图,这些位将被打包到您读取的字节中。这可能是与 C# 代码的另一个区别,其中每个位都可能被解压缩成一个完整的字节。在 MFC 版本中,您需要正确解释此数据。

于 2014-01-20T11:53:28.947 回答