【问题标题】:Unable to create image bitmap c++无法创建图像位图c ++
【发布时间】:2021-11-22 23:09:44
【问题描述】:

我的目标是按像素分析图像(以确定颜色)。我想在 C++ 中从图像路径创建位图:

string path = currImg.path;
cout << path << " " << endl;

然后我做了一些需要的类型更改,因为位图构造函数不接受简单的字符串类型:

wstring path_wstr = wstring(path.begin(), path.end()); 
const wchar_t* path_wchar_t = path_wstr.c_str();

最后构造Bitmap:

   Bitmap* img = new Bitmap(path_wchar_t);

在调试模式下,我看到 Bitmap 只是空:

如何构造 Bitmap 以逐像素扫描照片以了解每个像素的颜色?

【问题讨论】:

标签: c++ image bitmap pixel


【解决方案1】:

没有调用Gdiplus::GdiplusStartup,函数失败。或者文件名不存在并且函数失败。无论哪种方式img 都是NULL

上述代码中的文件名可能是错误的,因为 UTF16 转换错误。原始的 stringwstring 的副本只有在源是 ASCII 时才能工作。这很可能在非英语系统上失败(即使在英语系统上也很容易失败)。请改用MultiByteToWideChar。理想情况下,使用 UTF16 开头(虽然在控制台程序中有点困难)

int main()
{
    Gdiplus::GdiplusStartupInput tmp;
    ULONG_PTR token;
    Gdiplus::GdiplusStartup(&token, &tmp, NULL);
    test_gdi();
    Gdiplus::GdiplusShutdown(token);
    return 0;
} 

在继续之前进行测试以确保函数成功。

void test_gdi()
{
    std::string str = "c:\\path\\filename.bmp";
    int size = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, 0, 0);
    std::wstring u16(size, 0);
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, &u16[0], size);

    Gdiplus::Bitmap* bmp = new Gdiplus::Bitmap(u16.c_str());
    if (!bmp)
        return; //print error

    int w = bmp->GetWidth();
    int h = bmp->GetHeight();
    for (int y = 0; y < h; y++)
        for (int x = 0; x < w; x++)
        {
            Gdiplus::Color clr;
            bmp->GetPixel(x, y, &clr);
            auto red = clr.GetR();
            auto grn = clr.GetG();
            auto blu = clr.GetB();
        }
    delete bmp;
}

【讨论】:

    【解决方案2】:

    首先您需要提供位图图像文件格式的标题...然后逐字节读取。

    然后图像像素数据在标题结束的位置旁边。标头还包含像素数据开始位置的偏移量...

    然后您可以通过计算宽度高度和每个像素的字节数来一次读取像素数据...

    您还需要在行尾进行填充以考虑宽度不能被四整除的图像。

    基本上你需要写一个位图图像解析器...

    确保以二进制模式打开位图文件...

    更多信息在这里...

    https://en.wikipedia.org/wiki/BMP_file_format

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-09
      • 2021-11-17
      • 2019-05-01
      相关资源
      最近更新 更多