C ++ / Win32: Comment obtenir le canal alpha d'un HBITMAP?
Question
J'ai un HBITMAP
contenant des données de canal alpha. Je peux réussir à rendre ceci en utilisant la fonction GDI :: AlphaBlend
.
Cependant, lorsque j'appelle la fonction GDI :: GetPixel
, je ne récupère jamais de valeurs avec un composant alpha. La documentation indique qu’elle renvoie la valeur RVB du pixel.
Existe-t-il un moyen de récupérer les valeurs du canal alpha pour les pixels dans un HBITMAP
?
Je veux être capable de détecter quand utiliser :: AlphaBlend et quand utiliser une méthode traditionnelle pour traiter une couleur particulière de la source HBITMAP comme transparente.
HDC sourceHdc = ::CreateCompatibleDC(hdcDraw);
::SelectObject(sourceHdc, m_hbmp);
// This pixel has partial transparency, but ::GetPixel returns just RGB.
COLORREF c = ::GetPixel(sourceHdc, 20, 20);
// Draw the bitmap to hdcDraw
BLENDFUNCTION bf1;
bf1.BlendOp = AC_SRC_OVER;
bf1.BlendFlags = 0;
bf1.SourceConstantAlpha = 0xff;
bf1.AlphaFormat = AC_SRC_ALPHA;
::AlphaBlend(di.hdcDraw, x, 10, 64, 64, sourceHdc, 0, 0, 64, 64, bf1);
::DeleteDC(sourceHdc);
Répondre
Utilisez GetDIBits pour récupérer la (ou les) première (s) ligne (s) numérisée (s) de l'image:
byte* bits[1000];// = new byte[w * 4];
BITMAPINFO bmi;
memset(&bmi, 0, sizeof(BITMAPINFO));
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = w;
bmi.bmiHeader.biHeight = -h;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biSizeImage = 0;
bmi.bmiHeader.biXPelsPerMeter = 0;
bmi.bmiHeader.biYPelsPerMeter = 0;
bmi.bmiHeader.biClrUsed = 0;
bmi.bmiHeader.biClrImportant = 0;
int rv = ::GetDIBits(sourceHdc1, m_hbmp, 0, 1, (void**)&bits, &bmi, DIB_RGB_COLORS);
//bits[3] == alpha of topleft pixel;
//delete[] bits;
La solution
Utilisez GetDIBits. De cette façon, vous obtenez un tableau de RGBQUAD qui possède comme vous pouvez probablement deviner un canal alpha à côté des composants R, G et B.