有没有办法使用 ofstream 保存屏幕截图?
Is there a way I can save a screenshot using ofstream?
我正在尝试捕获屏幕截图,然后将其另存为bmp文件。
为什么保存文件时我的程序不起作用?
我将信息放入文件中并将其保存在项目所在的位置,但是当我打开文件时,什么也没出现。
我将不胜感激。
编辑:我已经更新了我的代码,但仍然不起作用,当我打开文件时,什么都没有再出现。
#include <iostream>
#include <Windows.h>
#include <fstream>
using namespace std;
int width = GetSystemMetrics(SM_CXSCREEN);
int height = GetSystemMetrics(SM_CYSCREEN);
string deskdir = "C:\Users\roile\Desktop\";
void screenshot()
{
HDC hScreen = GetDC(GetDesktopWindow());
HBITMAP hBitmap = CreateCompatibleBitmap(hScreen, width, height);
ofstream image;
image.open(deskdir + "Image.bmp", ios::binary);
image << hBitmap;
image.close();
}
int main()
{
screenshot();
return 0;
}
HBITMAP
是一个句柄。它类似于指针,它基本上是一个整数值,指向由操作系统管理的内存位置,其中存储了位图信息。此句柄仅适用于您自己的进程,它在进程存在后立即销毁。
您必须从此HBITMAP
句柄中提取位图信息和位。
请注意,完成后必须释放 GDI 句柄,否则程序会导致资源泄漏。
void screenshot()
{
SetProcessDPIAware();//for DPI awreness
RECT rc; GetClientRect(GetDesktopWindow(), &rc);
int width = rc.right;
int height = rc.bottom;
auto hdc = GetDC(0);
auto memdc = CreateCompatibleDC(hdc);
auto hbitmap = CreateCompatibleBitmap(hdc, width, height);
auto oldbmp = SelectObject(memdc, hbitmap);
BitBlt(memdc, 0, 0, width, height, hdc, 0, 0, SRCCOPY);
WORD bpp = 24; //save as 24bit image
int size = ((width * bpp + 31) / 32) * 4 * height; //adjust for padding
BYTE *bits = new BYTE[size]; //you can use std::vector instead of new to prevent leaks
BITMAPFILEHEADER bf = { 0 };
bf.bfType = (WORD)'MB';
bf.bfOffBits = 54;
bf.bfSize = bf.bfOffBits + size;
BITMAPINFOHEADER bi = { sizeof(bi), width, height, 1, bpp };
GetDIBits(hdc, hbitmap, 0, height, bits, (BITMAPINFO*)&bi, 0);
std::ofstream image("Image.bmp", ios::binary);
image.write((char*)&bf, sizeof(bf));
image.write((char*)&bi, sizeof(bi));
image.write((char*)bits, size);
delete[] bits;
SelectObject(memdc, oldbmp);
DeleteObject(hbitmap);
DeleteDC(memdc);
ReleaseDC(0, hdc);
}
相关文章:
- Winapi:屏幕截图未显示在窗口中
- 截取屏幕截图后程序卡住
- C++鼠标单击时的屏幕截图不起作用
- GTKMM:拍摄绘图区域的屏幕截图?
- 有没有办法使用 ofstream 保存屏幕截图?
- 如何使用 DX11 截取屏幕截图?
- avcodec_receive_packet错误(gdi 屏幕截图 + ffmpeg)
- C++屏幕截图 - 如何读取位图?
- 使用QT C 屏幕截图
- 如何将屏幕截图位图转换为 cv::Mat
- QT自动保存使用命名模板的屏幕截图
- C 屏幕截图
- BMP的完整屏幕截图.与块状和保存有关的问题
- 使用OpenCV和C++在按键上截取网络摄像头源的屏幕截图
- DirectX 部分屏幕截图
- 截取屏幕截图,分析它,然后删除它
- WXWIDGETS应用于WXStaticBitMap时,屏幕截图将大部分图像留为空白
- 在BMP文件中保存屏幕截图的设备上下文
- 如何使用自动命名保存屏幕截图
- Qt保存屏幕截图 - 命名问题