1
Graphics / Re: HBITMAP --> sf::Texture/sf::Image using ::loadFromMemory
« on: June 29, 2023, 07:27:50 am »
Here is what I did.
sf::Texture texture;
void shotScreen() {
int x = GetSystemMetrics(SM_XVIRTUALSCREEN);
int y = GetSystemMetrics(SM_YVIRTUALSCREEN);
int w = GetSystemMetrics(SM_CXVIRTUALSCREEN);
int h = GetSystemMetrics(SM_CYVIRTUALSCREEN);
HDC hScreen = GetDC(NULL);
HDC hDC = CreateCompatibleDC(hScreen);
HBITMAP hBitmap = CreateCompatibleBitmap(hScreen, w, h);
DeleteObject(SelectObject(hDC, hBitmap));
BOOL bRet = BitBlt(hDC, 0, 0, w, h, hScreen, x, y, SRCCOPY);
unsigned int dataSize = ((w * 32 + 31) / 32) * 4 * h;
BITMAPINFO Info = { sizeof(BITMAPINFOHEADER), static_cast<long>(w), static_cast<long>(0 - h), 1, 32, BI_RGB, dataSize, 0, 0, 0, 0 };
std::uint8_t* pixels = new std::uint8_t[dataSize];
int r = GetDIBits(hDC, hBitmap, 0, h, (LPVOID)pixels, &Info, DIB_RGB_COLORS);
for (int x = 0; x < dataSize; x += 4)
{
auto r = pixels[x + 2];
auto b = pixels[x];
pixels[x] = r;
pixels[x + 2] = b;
}
auto flag = texture.create(sf::Vector2u(w, h));
texture.update(pixels);
delete[] pixels;
DeleteDC(hDC);
ReleaseDC(NULL, hScreen);
DeleteObject(hBitmap);
}
void shotScreen() {
int x = GetSystemMetrics(SM_XVIRTUALSCREEN);
int y = GetSystemMetrics(SM_YVIRTUALSCREEN);
int w = GetSystemMetrics(SM_CXVIRTUALSCREEN);
int h = GetSystemMetrics(SM_CYVIRTUALSCREEN);
HDC hScreen = GetDC(NULL);
HDC hDC = CreateCompatibleDC(hScreen);
HBITMAP hBitmap = CreateCompatibleBitmap(hScreen, w, h);
DeleteObject(SelectObject(hDC, hBitmap));
BOOL bRet = BitBlt(hDC, 0, 0, w, h, hScreen, x, y, SRCCOPY);
unsigned int dataSize = ((w * 32 + 31) / 32) * 4 * h;
BITMAPINFO Info = { sizeof(BITMAPINFOHEADER), static_cast<long>(w), static_cast<long>(0 - h), 1, 32, BI_RGB, dataSize, 0, 0, 0, 0 };
std::uint8_t* pixels = new std::uint8_t[dataSize];
int r = GetDIBits(hDC, hBitmap, 0, h, (LPVOID)pixels, &Info, DIB_RGB_COLORS);
for (int x = 0; x < dataSize; x += 4)
{
auto r = pixels[x + 2];
auto b = pixels[x];
pixels[x] = r;
pixels[x + 2] = b;
}
auto flag = texture.create(sf::Vector2u(w, h));
texture.update(pixels);
delete[] pixels;
DeleteDC(hDC);
ReleaseDC(NULL, hScreen);
DeleteObject(hBitmap);
}