如何将GDI +的图像*转换为位图*

时间:2009-07-22 06:27:27

标签: c++ image gdi+ bitmap

我正在用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;
result = new Bitmap(width, height,PixelFormat32bppRGB);
Graphics gr(result);
//gr.SetInterpolationMode(InterpolationModeHighQuality);
gr.DrawImage(&sourceImg,0,0,width,height);

我真的不知道他们为什么不提供Image * - >位图*方法。但是让GetThumbnail()API返回一个Image对象....

3 个答案:

答案 0 :(得分:3)

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);
}

所有这些功能都可以在G ++ +的C ++版本中使用

答案 1 :(得分:3)

首先,您可以尝试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将是NULL),那么你可以尝试更通用的解决方案。

例如,使用Image方法将IStream保存到 COM Save,然后使用Bitmap::FromStreamBitmap创建IStream那条小溪。

可以使用CreateStreamOnHGlobal WinAPI 功能创建一个简单的 COM Image。然而,这不是很有效,特别是对于较大的流,但要测试它会做的想法。

还可以通过阅读ImageBitmap文档推断出其他类似的解决方案。

可悲的是,我没有亲自尝试过(Bitmap不是{{1}}),所以我不完全确定。

答案 2 :(得分:1)

据我所知,你必须创建一个位图并将图像绘制到其中:

Bitmap* GdiplusImageToBitmap(Image* img, Color bkgd = Color::Transparent)
{
    Bitmap* bmp = nullptr;
    try {
        int wd = img->GetWidth();
        int hgt = img->GetHeight();
        auto format = img->GetPixelFormat();
        Bitmap* 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;
}