2009-07-22 52 views
3

我在C++,gdi +中编写代码。如何将GDI +的图像*转换为位图*

我利用Image的GetThumbnail()方法来获取缩略图。 但是,我需要将其转换为HBITMAP。 我知道下面的代码可以得到GetHBITMAP:

Bitmap* img; 
HBITMAP temp; 
Color color; 
img->GetHBITMAP(color, &temp); // if img is Bitmap* this works well。 

但我怎么能转换图片*成位图*快? 非常感谢!

其实,现在我必须使用以下方法:

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

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

+4

你做的方式是好的。它之所以无法在一般情况下转换为“快速”,是因为“Image”根本不一定是位图 - 它可能是一个矢量图像(尽管我知道GDI +支持的唯一矢量格式是WMF/EMF)。我会想象在这种情况下,`GetThumbnail`也会产生一个矢量图像。 – 2009-07-22 08:16:55

+0

非常感谢!您的评论听起来合理! – user25749 2009-07-22 08:39:31

回答

3
Image* img = ???; 
Bitmap* bitmap = new Bitmap(img); 

编辑: 我看GDI +的the.NET参考,但这里是.NET如何实现这个构造。

using (Graphics graphics = null) 
{ 
    graphics = Graphics.FromImage(bitmap); 
    graphics.Clear(Color.Transparent); 
    graphics.DrawImage(img, 0, 0, width, height); 
} 

所有这些功能都在GDI的C++版本avaliable +

+1

我没有看到任何`Bitmap`构造函数接受`Image *`。 – 2009-07-22 07:04:34

2

首先,你可以尝试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. 

然而,如果不知它是不是(bitmapNULL),那么你可以尝试一个更通用的解决方案。

例如,Image保存到使用Save方法,然后使用Bitmap::FromStream从该流创建一个Bitmap COM IStream

简单COMIStream可以使用CreateStreamOnHGlobalWinAPI的函数创建。然而,这并不是有效的,特别是对于较大的数据流,而是测试它会做的想法。

还有其他类似的解决方案,可以从ImageBitmap文档中推导出来。

可悲的是我还没有尝试过我自己的(与Image这不是Bitmap),所以我不完全确定。

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