我正在用 c++、gdi+ 编写代码。
我利用Image的GetThumbnail()方法来获取缩略图。 但是,我需要将其转换为 HBITMAP。 我知道下面的代码可以获取GetHBITMAP:
Bitmap* img;
HBITMAP temp;
Color color;
img->GetHBITMAP(color, &temp); // if img is Bitmap* this works well。
但是如何快速将 Image* 转换为 Bitmap* 呢? 非常感谢!
其实,现在我必须使用以下方法:
int width = sourceImg->GetWidth(); // sourceImg is Image*
int height = sourceImg->GetHeight();
Bitmap* result = new Bitmap(width, height,PixelFormat32bppRGB);
Graphics gr(result);
//gr.SetInterpolationMode(InterpolationModeHighQuality);
gr.DrawImage(sourceImg, 0, 0, width, height);
我真的不知道为什么他们不提供 Image* -> Bitmap* 方法。但让 GetThumbnail() API 返回一个 Image 对象....
Image* img = ???;
Bitmap* bitmap = new Bitmap(img);
编辑: 我正在查看 GDI+ 的 .NET 参考,但以下是 .NET 实现该构造函数的方式。
using (Graphics graphics = null)
{
graphics = Graphics.FromImage(bitmap);
graphics.Clear(Color.Transparent);
graphics.DrawImage(img, 0, 0, width, height);
}
所有这些功能都可以在 GDI+ 的 C++ 版本中使用
首先,您可以尝试
dynamic_cast
,因为在许多情况下(如果不是大多数 - 至少在我的用例中)Image
正在由 Bitmap
实现。所以
Image* img = getThumbnail( /* ... */ );
Bitmap* bitmap = dynamic_cast<Bitmap*>(img);
if(!bitmap)
// getThumbnail returned an Image which is not a Bitmap. Convert.
else
// getThumbnail returned a Bitmap so just deal with it.
但是,如果不知何故不是(
bitmap
将是nullptr
)那么你可以尝试更通用的解决方案。
例如,使用
Image
方法将 IStream
保存到 COM
Save
,然后使用 Bitmap::FromStream
从该流创建 Bitmap
。
可以使用 IStream
函数创建一个简单的COM
CreateStreamOnHGlobal
。然而,这效率不高,尤其是对于较大的流,但要测试它的想法。
Image
和 Bitmap
文档推导出来。
遗憾的是,我还没有亲自尝试过(使用
Image
,这不是Bitmap
),所以我不完全确定。
据我所知,您只需创建一个位图并将图像绘制到其中即可:
Bitmap* GdiplusImageToBitmap(Image* img, Color bkgd = Color::Transparent)
{
Bitmap* bmp = nullptr;
try {
int wd = img->GetWidth();
int hgt = img->GetHeight();
auto format = img->GetPixelFormat();
bmp = new Bitmap(wd, hgt, format);
auto g = std::unique_ptr<Graphics>(Graphics::FromImage(bmp));
g->Clear(bkgd);
g->DrawImage(img, 0, 0, wd, hgt);
} catch(...) {
// this might happen if img->GetPixelFormat() is something exotic
// ... not sure
}
return bmp;
}