我有一个dev-c++应用程序,它可以制作屏幕截图并将其写入文件。现在我想将图像写入变量/流。最初我使用了三个Writefile
函数,它们将标头,信息和hbitmap写入一个文件。现在,我想将数据保存到流中,而不是保存到文件中,以便我可以使用它进行进一步处理。我使用的代码是这样的:
/* <Include> */
#include <windows.h>
#include <iostream>
#include <sstream>
/* </Include> */
/* <Const> */
const char *AppName="Yeah";
using namespace std;
/* </Const> */
/* <Function> */
void SaveScreen(HWND pScreen, stringstream Path)
{
int Width = GetSystemMetrics(SM_CXSCREEN);//1280;
int Height = GetSystemMetrics(SM_CYSCREEN);//1024;
HDC hdcScreen;
HBITMAP hbmScreen;
//---------------Bitmap Informationen
BITMAPINFO infobmp;
infobmp.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
infobmp.bmiHeader.biWidth = Width;
infobmp.bmiHeader.biHeight = Height;
infobmp.bmiHeader.biPlanes = 1;
infobmp.bmiHeader.biBitCount = 24;
infobmp.bmiHeader.biCompression = 0;
infobmp.bmiHeader.biSizeImage = 0;
infobmp.bmiHeader.biXPelsPerMeter = 0;
infobmp.bmiHeader.biYPelsPerMeter = 0;
infobmp.bmiHeader.biClrUsed = 0;
infobmp.bmiHeader.biClrImportant = 0;
int* bitmap = new int[Width*Height*3];
BITMAPFILEHEADER bfheader;
bfheader.bfType = 19778;
bfheader.bfSize = sizeof(BITMAPFILEHEADER) + Width*Height*3 + sizeof(BITMAPINFOHEADER);
bfheader.bfReserved1 = 0;
bfheader.bfReserved2 = 0;
bfheader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
//Bitmap ----------------------- Informationen
hdcScreen = GetWindowDC(pScreen);
hbmScreen = CreateCompatibleBitmap(hdcScreen, Width, Height);
// tempor?rer DC
HDC hdcTemp = CreateCompatibleDC(hdcScreen);
// Bitmap reinselektieren
HBITMAP hbmOld = (HBITMAP)SelectObject(hdcTemp, hbmScreen);
// Inhalt von Desktop ?bertragen
BitBlt(hdcTemp, 0, 0, Width, Height, hdcScreen, 0, 0, SRCCOPY);
int iResult = GetDIBits(hdcTemp, hbmScreen, 0, Height, bitmap, &infobmp, DIB_RGB_COLORS);
// aufr?umen
SelectObject(hdcTemp, hbmOld);
DeleteObject(hbmScreen);
DeleteDC(hdcTemp);
// HANDLE hfile = CreateFile(Path, GENERIC_WRITE, 0, 0, OPEN_ALWAYS, 0, 0);
//Datei Schreiben
DWORD word;
WriteFile(Path, &bfheader, 14, &word, NULL);
WriteFile(Path, &infobmp, 40,& word, NULL);
WriteFile(Path, bitmap, Width*Height*3, &word,NULL);
// Path = &bfheader & &infobmp & bitmap;
ReleaseDC(pScreen, hdcScreen);
// CloseHandle(hfile);
delete[] bitmap;
}
/* </Function> */
int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
HWND hWnd = FindWindow(NULL, AppName);
stringstream ms;
SaveScreen(hWnd, ms);
return 0;
}
有人可以告诉我我做错了什么吗?
您可以创建如下结构:
struct ScreenShotBuffer
{
BITMAPFILEHEADER bfheader;
BITMAPINFO infobmp;
int* bitmap;
};
然后使用该结构创建一个全局变量。
struct ScreenShotBuffer myScreenShot;
无论如何,您正在使用malloc分配"内存"来保存数据。所以你可以只用这三行而不是WriteBuffer()
:
myScreenShot.bfheader=bfheader;
myScreenShot.infobmp=infobmp;
myScreenShot.bitmap=bitmap;