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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值