QImage from HBITMAP
Asked Answered
S

4

7

In my windows-only program, I use a third-party library, which returns a HBITMAP.

Is there a way to initialize a QImage from its contents, i.e. to convert it to a QImage?

Sphacelus answered 28/1, 2013 at 18:24 Comment(0)
C
11

This is the way to do it for Qt 4 (QtGui):

QImage image(QPixmap::fromWinHBITMAP(hBitmap).toImage());

This is the way to do it for Qt 5 (QtWinExtras):

QPixmap pixmap = QtWin::fromHBITMAP(hBitmap);
QImage image = pixmap.toImage();

// or

QtWin::imageFromHBITMAP(hdc, hBitmap, width, height)
Cryptography answered 17/12, 2013 at 16:46 Comment(1)
For Qt 6 fromWinHBITMAP is now part of QImage natively, so you can just call QImage.fromHBITMAP.Bataan
S
3

OK, this seems to work for me:

QImage image(QPixmap::fromWinHBITMAP(hBitmap).toImage());
Sphacelus answered 28/1, 2013 at 18:33 Comment(1)
This is not available after Qt 4.8Lippi
S
1

Qt5 without Extras: Put before your code

#include <QPixmap>
Q_GUI_EXPORT QPixmap qt_pixmapFromWinHBITMAP(HBITMAP bitmap, int hbitmapFormat=0);

and in your function, for example

QPixmap pixmap = qt_pixmapFromWinHBITMAP(LoadBitmap(uiID));

Cheers

Splendent answered 13/10, 2015 at 9:53 Comment(1)
This is not a public API.Novara
C
1

As of Qt 6.0, you could use the static QImage::fromHBITMAP(HBITMAP hbitmap):

Returns a QImage that is equivalent to the given hbitmap.

HBITMAP does not store information about the alpha channel.

In the standard case, the alpha channel is ignored and a fully opaque image is created (typically of >format QImage::Format_RGB32).

There are cases where the alpha channel is used, though, for example for application icon or systray icons. In that case, reinterpretAsFormat(QImage::Format_ARGB32) should be called on the returned image to ensure the format is correct.

This function was introduced in Qt 6.0.

Cozy answered 8/11, 2023 at 17:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.