2009-07-22 51 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; 
}