How to convert GDI + image * to bitmap *

I am writing code in C ++, gdi +.

I use the Image method GetThumbnail () to get a sketch. However, I need to convert it to HBITMAP. I know that the following code can get GetHBITMAP:

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

But how can I quickly convert Image * to Bitmap *? Many thanks!

Actually, now I have to use the following method:

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

I really don't know why they do not provide the Image * -> Bitmap * method. but let the GetThumbnail () API return an Image object ....

+3
source share
3 answers
Image* img = ???;
Bitmap* bitmap = new Bitmap(img);

Edit: I was looking at the .NET link in GDI +, but here's how .NET implements this constructor.

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

All these functions are available in the C ++ version for C ++ +.

+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 COM IStream Save, Bitmap::FromStream Bitmap .

COM IStream CreateStreamOnHGlobal WinAPI. , , , .

, Image Bitmap.

, ( Image, Bitmap), .

+2

As far as I can tell, you just need to create a bitmap image and draw an image in it:

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;
}
+1
source

Source: https://habr.com/ru/post/1713207/


All Articles