I'm trying to write an application for storing screenshots on an external server, but due to limited resources, I'd like to store them in text form, specifically as BYTE* array. As a result, I've encountered some issues related to reading the screenshots uploaded to the server. I can read and save any screenshot I took during a session at any time on my computer, but screenshots taken by my friend are created as 0kb files without content and cause the application to crash during the execution of the function responsible for scanning rows...
LPBYTE SaveScreenshotNew()
{
int nScreenWidth = GetSystemMetrics(SM_CXSCREEN);
int nScreenHeight = GetSystemMetrics(SM_CYSCREEN);
HDC hdcScreen = GetDC(NULL);
HDC hdcMem = CreateCompatibleDC(hdcScreen);
HBITMAP hBitmap = CreateCompatibleBitmap(hdcScreen, nScreenWidth, nScreenHeight);
SelectObject(hdcMem, hBitmap);
BitBlt(hdcMem, 0, 0, nScreenWidth, nScreenHeight, hdcScreen, 0, 0, SRCCOPY);
int bufferSize = nScreenWidth * nScreenHeight * 3;
LPBYTE buffer = new BYTE[bufferSize];
BITMAPINFOHEADER bi;
memset(&bi, 0, sizeof(BITMAPINFOHEADER));
bi.biSize = sizeof(BITMAPINFOHEADER);
bi.biWidth = nScreenWidth;
bi.biHeight = -nScreenHeight;
bi.biPlanes = 1;
bi.biBitCount = 24;
bi.biCompression = BI_RGB;
bi.biSizeImage = 0;
if (GetDIBits(hdcScreen, hBitmap, 0, nScreenHeight, buffer, (BITMAPINFO*)&bi, DIB_RGB_COLORS) != 0) {
for (int i = 0; i < nScreenHeight; i++) {
for (int j = 0; j < nScreenWidth; j++) {
int index = i * nScreenWidth * 3 + j * 3;
BYTE blue = buffer[index];
buffer[index] = buffer[index + 2];
buffer[index + 2] = blue;
}
}
}
DeleteObject(hBitmap);
DeleteDC(hdcMem);
ReleaseDC(NULL, hdcScreen);
return buffer;
}
jpeglib code:
FILE* outfile = fopen(szPath, "wb");
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);
jpeg_stdio_dest(&cinfo, outfile);
cinfo.image_width = sWidth;
cinfo.image_height = sHeight;
cinfo.input_components = 3;
cinfo.in_color_space = JCS_RGB;
jpeg_set_defaults(&cinfo);
jpeg_start_compress(&cinfo, TRUE);
while (cinfo.next_scanline < cinfo.image_height) {
JSAMPROW row_pointer = &gScreenPacket.lpData[cinfo.next_scanline * cinfo.image_width * cinfo.input_components];
jpeg_write_scanlines(&cinfo, &row_pointer, 1);
}
jpeg_finish_compress(&cinfo);
jpeg_destroy_compress(&cinfo);
fclose(outfile);
I've tried:
increasing/decreasing the buffer size, changing the screenshot saving function, using a different available function in jpeglib.
Tyvm for your help.
Not related with your crash, but there are easier ways of creating jpeg image from screenshot in Windows. Using GDI+ is one of them. I prepared a working example from this for VS2019 as below: