c++ - Convert LPVOID bitmap pointer to QPixmap
问题描述
I am trying to load in a BMP image from a resources folder into a QPixmap object. However, I can't read the bytes even though rewriting those bytes to a new file makes a correct copy of the original. Here is my loading method:
QPixmap* GUIMain::loadImage(int name) {
// Resource loading, works fine
HRSRC rc = FindResource(NULL, MAKEINTRESOURCE(name), RT_BITMAP);
if (rc == NULL) {
printf("INVALID RESOURCE ADDRESS (%i)\n", name);
return new QPixmap();
}
HGLOBAL rcData = LoadResource(NULL, rc);
LPVOID data = LockResource(rcData);
DWORD data_size = SizeofResource(NULL, rc);
// Rewrite file to new file, works fine
ofstream output("E:\\" + to_string(name) + ".bmp", std::ios::binary);
BITMAPFILEHEADER bfh = { 'MB', 54 + data_size, 0, 0, 54 };
output.write((char*)&bfh, sizeof(bfh));
output.write((char*)data, data_size);
output.close();
// Need to return, can't get bytes working
return new QPixmap(/*?*/);
}
This method is called with the definitions from the resource.h
file.
I have tried to use a stringstream
with the same calls as the ofstream
, followed by using that stream as a source for the QPixmap
, but the stream didn't produce the same output.
Here are the relevant parts of my resource.h
file:
#define IDB_BITMAP1 101
#define IDB_BITMAP2 102
Here is my Resource.rc
file:
IDB_BITMAP1 BITMAP "E:\\Downloads\\onIcon.bmp"
IDB_BITMAP2 BITMAP "E:\\Downloads\\offIcon.bmp"
I know I should be using the Qt tools for resource management, but I don't have the capabilities to do so.
解决方案
您可以使用 QPixmap::loadFromData(...) 从 bmp 格式的字节创建 QPixmap,但您也不需要在 .rc 文件中将资源声明为“BITMAP”。
位图资源旨在与LoadBitmap(...)或LoadImage(...)一起使用,并存储在 .exe 中,并去掉位图标头。(Raymond Chen 在这里讨论这个)由于您没有使用 LoadBitmap 将资源的类型设置为任意二进制数据,例如
IDB_BITMAP1 RCDATA "E:\\Downloads\\onIcon.bmp"
然后实现您的图像加载例程,如下所示:
QPixmap* GUIMain::loadImage(int name) {
// ...
HGLOBAL rcData = LoadResource(NULL, rc);
LPVOID data = LockResource(rcData);
DWORD data_size = SizeofResource(NULL, rc);
QPixmap* pm = new QPixmap();
pm->loadFromData( static_cast<uchar*>(data), data_size, "bmp");
return pm;
}
推荐阅读
- flexbox - 如何在 VBox 中居中 Text 或 FormattedText 并让文本在每一行的相同位置开始?
- linux - 如何将 korn 作业限制为仅从晚上 10 点到凌晨 12 点运行
- python - 为什么我的 for 循环包含一个简单的 while 循环只运行两次?而且很差
- angular - 升级Angular和项目后找不到编译器ngcc模块
- javascript - 是否有计算或估计二进制整数位数的公式?
- ios - 以编程方式在 UITabbarController 中使用自定义 UITabbar
- javascript - 如何在给定字符串之前和之后替换除 100 个字符之外的所有内容?
- react-native - 将 Enzyme 与 React Native 一起使用时出错(导入 glyphmap)
- apache-spark - 既然 SparkSession 是唯一的入口点,为什么 SparkContext 仍然可用?
- reactjs - 将 this.props.history.push 传递给另一个组件的一个变量中的属性。反应 JS