c++ - 来自 std::vector<std::uint32_t> 保存数组中原始 RGB 值的 CBitmap

标签 c++ image bitmap mfc

我在网上找到的库中的以下代码中有原始 RGBA 值的位图。 "svgren.

auto img = svgren::render(*dom, width, height); //uses 96 dpi by default
//At this point the 'width' and 'height' variables were filled with
//the actual width and height of the rendered image.
//Returned 'img' is a std::vector<std::uint32_t> holding array of RGBA values.

我需要知道如何将这张图片放入 CBitmap 中,以便我可以在 MFC Picture 控件中显示它。我可以预先确定它的大小,并且我知道如何在控件中显示位图。我不能做的是将 RGBA 值加载到位图中。有什么想法吗?

最佳答案

CBitmap::CreateBitmap成员函数可以从一 block 内存构造位图。 lpBits 参数需要一个指向 byte 值的指针。将指针传递给 uint32_t 值数组在技术上是未定义的行为(尽管它适用于 Windows 的所有小端实现)。

必须特别注意内存布局。这仅记录了 Windows API 调用 CreateBitmap并且根本不存在于 MFC 文档中:

Each scan line in the rectangle must be word1 aligned (scan lines that are not word aligned must be padded with zeros).

基于内存正确对齐的假设,并且将缓冲区重新解释为指向字节的指针已明确定义,这是一个具有适当资源处理的实现:

CBitmap Chb;
Chb.CreateBitmap(width, height, 1, 32, img.data());
mProjectorWindow.m_picControl.ModifyStyle(0xF, SS_BITMAP, SWP_NOSIZE);
Chb.Attach(mProjectorWindow.m_picControl.SetBitmap(Chb.Detach()));

最后一行代码在 m_picControlChb 之间交换 GDI 资源的所有权。这确保正确清理以前由 m_picControl 拥有的 GDI 资源,并使 m_picControl 成为新创建的位图的唯一所有者。


1 我相信这个should read dword aligned .

关于c++ - 来自 std::vector<std::uint32_t> 保存数组中原始 RGB 值的 CBitmap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39479323/

相关文章:

Android 位图工厂内存不足第二张照片

c++ - 无法通过引用传递值 C++

c++ - 在循环内声明变量,好的做法还是坏的做法?

image - 选择霍夫变换的参数

html - CSS:如何在内容的左侧和右侧制作背景

c# - 位图的 OutOfMemoryException 错误

.net - Compact Framework - Image.FromStream (Stream, Boolean, Boolean) 的任何实现?

c++ - 函数不读取二维数组的 [i][0] 行

c++ - 我应该使用 cstdint 吗?

android - 如何通过任何文件资源管理器更改图像背景