HBITMAP转RGBA pixels

static std::vector<char> ConvertToBGRAPixels(HBITMAP BitmapHandle)
{
    
    
  BITMAP Bmp      = {
    
    0};
  BITMAPINFO Info = {
    
    0};
  std::vector<char> Pixels;

  HDC DC = CreateCompatibleDC(NULL);
  std::memset(&Info, 0, sizeof(BITMAPINFO)); // not necessary really..
  HBITMAP OldBitmap = (HBITMAP)SelectObject(DC, BitmapHandle);
  GetObject(BitmapHandle, sizeof(Bmp), &Bmp);

  Info.bmiHeader.biSize        = sizeof(BITMAPINFOHEADER);
  Info.bmiHeader.biWidth       = Bmp.bmWidth;
  Info.bmiHeader.biHeight      = Bmp.bmHeight;
  Info.bmiHeader.biPlanes      = 1;
  Info.bmiHeader.biBitCount    = Bmp.bmBitsPixel;
  Info.bmiHeader.biCompression = BI_RGB;
  Info.bmiHeader.biSizeImage   = ((Bmp.bmWidth * Bmp.bmBitsPixel + 31) / 32) * 4 * Bmp.bmHeight;

  Pixels.resize(Info.bmiHeader.biSizeImage);

#  if 1 // to RGBA pixels
  const char* pixelsBGRA = (const char*)Bmp.bmBits;
  char* pixeslRGBA       = &Pixels[0];
  const int bytesPerPixel = 4;
  int count               = Info.bmiHeader.biSizeImage / bytesPerPixel;
  for (size_t i = 0; i < count; i++)
  {
    
    
    const unsigned char alpha = pixelsBGRA[3];
    // Input is BGRA, output is RGBA
    pixeslRGBA[2] = pixelsBGRA[0];
    pixeslRGBA[1] = pixelsBGRA[1];
    pixeslRGBA[0] = pixelsBGRA[2];
    pixeslRGBA[3] = alpha;
    pixeslRGBA += bytesPerPixel;
    pixelsBGRA += bytesPerPixel;
  }
#  else
  // BGRA pixels
  GetDIBits(DC, BitmapHandle, 0, Bmp.bmHeight, &Pixels[0], &Info, DIB_RGB_COLORS);
#  endif
  SelectObject(DC, OldBitmap);
  DeleteDC(DC);
  return Pixels;
}

猜你喜欢

转载自blog.csdn.net/xyzzf/article/details/114196346
今日推荐