Ian Engebrecht Ian Engebrecht - 3 years ago 167
C++ Question

Convert GDI Plus Bitmap to QPixmap

I have a GdiPlus::Bitmap object, and I need to build a function that converts it to a QPixmap. I'm using Qt 5.8.0, and performance is a concern of mine. I cannot find anything about this online, even searching for GDI+ images to QImages. I don't NEED to access pixel data, so all I have to do is get a GDI+ bitmap converted into something that can be displayed in a QWidget.

The most promising solution I've found so far is to use the fromHBitMap() in QtWin: http://doc.qt.io/qt-5/qtwin.html#fromHBITMAP, but I don't have the required knowledge/experience to be able to understand handles to bitmaps.

Answer Source

I had a method of doing this where I flipped the red and blue bytes, then used the following code to convert it from a Gdiplus::Bitmap to a QPixmap:

QPixmap getAsQPixmap(Gdiplus::Bitmap bitmap)
{
   // One of my functions to flip blue and red bytes of the image
   _flipBlueWithRed();

   // m_pBytes is a pointer to an unsigned char that marks the start of the image
   // It was retrieved from locking the Gdiplus::Bitmap
   auto result = QPixmap::fromImage(QImage(m_pBytes, getWidth(), getHeight(), QImage::Format_RGB888));

   // Restore data back to original state
   _flipBlueWithRed();

   return result;
}

This method, however, was slow and took a good 60 milliseconds to execute. So my new method was to save the Gdiplus::Bitmap to file, and use the path to that file to read in from QPixmap's constructor. This method is MUCH faster, around 5 milliseconds.

QPixmap getAsQPixmap(GdiPlus::Bitmap bitmap)
{
    std::string path = "C:/path_to_img.....png";

    // One of my functions to unlock the Gdi+ bitmap
    _unlockGdiPlusBitmap();

    // Get Clsid
    CLSID pngClsid;
    getEncoderClsid(format_mime, &pngClsid);

    // Save bitmap
    // stringToWString() was a function that I wrote to convert a standard string to be a wide string
    bitmap->Save(stringToWString(path).c_str(), static_cast<const CLSID*>(&pngClsid));

    // Lock bitmap
    _lockGdiPlusBitmap();

    // Create the QPixmap
    QPixmap new_img(path);

    return new_img;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download