C++实现截图截屏的示例代码

目录
  • 1、截图工具
    • 1.1 键盘截图(PrtScn键)
    • 1.2 win10自带截图(Win+Shift+S)
    • 1.3 系统自带的截图小工具
    • 1.4 ffmpeg
    • 1.5 ScreenToGif
    • 1.6 Chrome
  • 2、C++、GDI
    • 2.1 微软官方例子
    • 2.2 C++、GDI、CImage
  • 3、C++、OpenGL
  • 4、C++、OpenCV
  • 5、C++、QT

1、截图工具

1.1 键盘截图(PrtScn键)

如何使用Microsoft Windows操作系统中的Print Screen(打印屏幕)键
(1)Print Screen键
按下之后,截取整个屏幕的画面到剪切板里。可以复制到其他软件里,比如系统的画图工具,Office Word等。

(2)Alt+Print Screen组合键
按下之后,截取当前活动窗口的画面到剪切板里。

1.2 win10自带截图(Win+Shift+S)

按下该组合键之后,使用鼠标在屏幕上画出想要截取的矩形区域,自动保存到系统剪切板里。

1.3 系统自带的截图小工具

1.4 ffmpeg

ffmpeg -i “输入视频” -fflags nobuffer -t 60 -ss 0 “输出地址”
说明:代表截取输入视频从0秒到60秒的片段,保存到输出地址。
-ss n : 起始时间为第n秒
-t n : 总共截取的片段时长为n秒

运行后会生成截图: out1.jpg out2.jpg out3.jpg …

ffmpeg -i fight.mp4 -r 1 -t 200 -ss 1 -f image2 out%d.jpg

1.5 ScreenToGif

1.6 Chrome

2、C++、GDI

2.1 微软官方例子

https://docs.microsoft.com/en-us/windows/win32/gdi/capturing-an-image

int CaptureAnImage(HWND hWnd)
{
    HDC hdcScreen;
    HDC hdcWindow;
    HDC hdcMemDC = NULL;
    HBITMAP hbmScreen = NULL;
    BITMAP bmpScreen;
    DWORD dwBytesWritten = 0;
    DWORD dwSizeofDIB = 0;
    HANDLE hFile = NULL;
    char* lpbitmap = NULL;
    HANDLE hDIB = NULL;
    DWORD dwBmpSize = 0;

    // Retrieve the handle to a display device context for the client
    // area of the window.
    hdcScreen = GetDC(NULL);
    hdcWindow = GetDC(hWnd);

    // Create a compatible DC, which is used in a BitBlt from the window DC.
    hdcMemDC = CreateCompatibleDC(hdcWindow);

    if (!hdcMemDC)
    {
        MessageBox(hWnd, L"CreateCompatibleDC has failed", L"Failed", MB_OK);
        goto done;
    }

    // Get the client area for size calculation.
    RECT rcClient;
    GetClientRect(hWnd, &rcClient);

    // This is the best stretch mode.
    SetStretchBltMode(hdcWindow, HALFTONE);

    // The source DC is the entire screen, and the destination DC is the current window (HWND).
    if (!StretchBlt(hdcWindow,
        0, 0,
        rcClient.right, rcClient.bottom,
        hdcScreen,
        0, 0,
        GetSystemMetrics(SM_CXSCREEN),
        GetSystemMetrics(SM_CYSCREEN),
        SRCCOPY))
    {
        MessageBox(hWnd, L"StretchBlt has failed", L"Failed", MB_OK);
        goto done;
    }

    // Create a compatible bitmap from the Window DC.
    hbmScreen = CreateCompatibleBitmap(hdcWindow, rcClient.right - rcClient.left, rcClient.bottom - rcClient.top);

    if (!hbmScreen)
    {
        MessageBox(hWnd, L"CreateCompatibleBitmap Failed", L"Failed", MB_OK);
        goto done;
    }

    // Select the compatible bitmap into the compatible memory DC.
    SelectObject(hdcMemDC, hbmScreen);

    // Bit block transfer into our compatible memory DC.
    if (!BitBlt(hdcMemDC,
        0, 0,
        rcClient.right - rcClient.left, rcClient.bottom - rcClient.top,
        hdcWindow,
        0, 0,
        SRCCOPY))
    {
        MessageBox(hWnd, L"BitBlt has failed", L"Failed", MB_OK);
        goto done;
    }

    // Get the BITMAP from the HBITMAP.
    GetObject(hbmScreen, sizeof(BITMAP), &bmpScreen);

    BITMAPFILEHEADER   bmfHeader;
    BITMAPINFOHEADER   bi;

    bi.biSize = sizeof(BITMAPINFOHEADER);
    bi.biWidth = bmpScreen.bmWidth;
    bi.biHeight = bmpScreen.bmHeight;
    bi.biPlanes = 1;
    bi.biBitCount = 32;
    bi.biCompression = BI_RGB;
    bi.biSizeImage = 0;
    bi.biXPelsPerMeter = 0;
    bi.biYPelsPerMeter = 0;
    bi.biClrUsed = 0;
    bi.biClrImportant = 0;

    dwBmpSize = ((bmpScreen.bmWidth * bi.biBitCount + 31) / 32) * 4 * bmpScreen.bmHeight;

    // Starting with 32-bit Windows, GlobalAlloc and LocalAlloc are implemented as wrapper functions that
    // call HeapAlloc using a handle to the process's default heap. Therefore, GlobalAlloc and LocalAlloc
    // have greater overhead than HeapAlloc.
    hDIB = GlobalAlloc(GHND, dwBmpSize);
    lpbitmap = (char*)GlobalLock(hDIB);

    // Gets the "bits" from the bitmap, and copies them into a buffer
    // that's pointed to by lpbitmap.
    GetDIBits(hdcWindow, hbmScreen, 0,
        (UINT)bmpScreen.bmHeight,
        lpbitmap,
        (BITMAPINFO*)&bi, DIB_RGB_COLORS);

    // A file is created, this is where we will save the screen capture.
    hFile = CreateFile(L"captureqwsx.bmp",
        GENERIC_WRITE,
        0,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL, NULL);

    // Add the size of the headers to the size of the bitmap to get the total file size.
    dwSizeofDIB = dwBmpSize + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);

    // Offset to where the actual bitmap bits start.
    bmfHeader.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + (DWORD)sizeof(BITMAPINFOHEADER);

    // Size of the file.
    bmfHeader.bfSize = dwSizeofDIB;

    // bfType must always be BM for Bitmaps.
    bmfHeader.bfType = 0x4D42; // BM.

    WriteFile(hFile, (LPSTR)&bmfHeader, sizeof(BITMAPFILEHEADER), &dwBytesWritten, NULL);
    WriteFile(hFile, (LPSTR)&bi, sizeof(BITMAPINFOHEADER), &dwBytesWritten, NULL);
    WriteFile(hFile, (LPSTR)lpbitmap, dwBmpSize, &dwBytesWritten, NULL);

    // Unlock and Free the DIB from the heap.
    GlobalUnlock(hDIB);
    GlobalFree(hDIB);

    // Close the handle for the file that was created.
    CloseHandle(hFile);

    // Clean up.
done:
    DeleteObject(hbmScreen);
    DeleteObject(hdcMemDC);
    ReleaseDC(NULL, hdcScreen);
    ReleaseDC(hWnd, hdcWindow);

    return 0;
}

2.2 C++、GDI、CImage

HDC hdcSrc = GetDC(NULL);
int nBitPerPixel = GetDeviceCaps(hdcSrc, BITSPIXEL);
int nWidth = GetDeviceCaps(hdcSrc, HORZRES);
int nHeight = GetDeviceCaps(hdcSrc, VERTRES);
CImage image;
image.Create(nWidth, nHeight, nBitPerPixel);
BitBlt(image.GetDC(), 0, 0, nWidth, nHeight, hdcSrc, 0, 0, SRCCOPY);
ReleaseDC(NULL, hdcSrc);
image.ReleaseDC();
image.Save(s, Gdiplus::ImageFormatPNG);

3、C++、OpenGL

void CaptureOpenGLWindow(const char* savePath, int w, int h)
{
	GLubyte* pPixelData;
	GLint    PixelDataLength;  

	// 分配内存和打开文件
	pPixelData = (GLubyte*)malloc(w*h*3);
	if (pPixelData == 0)
		return;

	glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
	glReadPixels(0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, pPixelData);
	stbi_write_png(savePath, w, h, 3, pPixelData, 0);
	free(pPixelData);

	int iw = w, ih = h, n = 3;
	stbi_set_flip_vertically_on_load(true);
	unsigned char *idata = stbi_load(savePath, &iw, &ih, &n, 0);
	stbi_write_png(savePath, w, h, 3, idata, 0);
	stbi_image_free(idata);

}

4、C++、OpenCV

BITMAPINFOHEADER createBitmapHeader(int width, int height)
{
   BITMAPINFOHEADER  bi;

     // create a bitmap
     bi.biSize = sizeof(BITMAPINFOHEADER);
     bi.biWidth = width;
     bi.biHeight = -height;  //this is the line that makes it draw upside down or not
     bi.biPlanes = 1;
     bi.biBitCount = 32;
     bi.biCompression = BI_RGB;
     bi.biSizeImage = 0;
     bi.biXPelsPerMeter = 0;
     bi.biYPelsPerMeter = 0;
     bi.biClrUsed = 0;
     bi.biClrImportant = 0;

     return bi;
}

Mat captureScreenMat(HWND hwnd)
{
     Mat src;

     // get handles to a device context (DC)
     HDC hwindowDC = GetDC(hwnd);
     HDC hwindowCompatibleDC = CreateCompatibleDC(hwindowDC);
     SetStretchBltMode(hwindowCompatibleDC, COLORONCOLOR);

     // define scale, height and width
     int screenx = GetSystemMetrics(SM_XVIRTUALSCREEN);
     int screeny = GetSystemMetrics(SM_YVIRTUALSCREEN);
     int width = GetSystemMetrics(SM_CXVIRTUALSCREEN);
     int height = GetSystemMetrics(SM_CYVIRTUALSCREEN);

     // create mat object
     src.create(height, width, CV_8UC4);

     // create a bitmap
     HBITMAP hbwindow = CreateCompatibleBitmap(hwindowDC, width, height);
     BITMAPINFOHEADER bi = createBitmapHeader(width, height);

     // use the previously created device context with the bitmap
     SelectObject(hwindowCompatibleDC, hbwindow);

     // copy from the window device context to the bitmap device context
     StretchBlt(hwindowCompatibleDC, 0, 0, width, height, hwindowDC, screenx, screeny, width, height, SRCCOPY);  //change SRCCOPY to NOTSRCCOPY for wacky colors !
     GetDIBits(hwindowCompatibleDC, hbwindow, 0, height, src.data, (BITMAPINFO*)&bi, DIB_RGB_COLORS);            //copy from hwindowCompatibleDC to hbwindow

     // avoid memory leak
     DeleteObject(hbwindow);
     DeleteDC(hwindowCompatibleDC);
     ReleaseDC(hwnd, hwindowDC);

     return src;
 }
 int main()
{
      // capture image
      HWND hwnd = GetDesktopWindow();
      Mat src = captureScreenMat(hwnd);

      // save img
      cv::imwrite("Screenshot.png", src);

  	  // clean-ups
      buf.clear();
      return 0;
}

5、C++、QT

QDesktopWidget *desk = QApplication::desktop();
QScreen * screen = QGuiApplication::primaryScreen();
QPixmap p = screen->grabWindow(desk->winId());
QImage image = p.toImage();

到此这篇关于C++实现截图截屏的示例代码的文章就介绍到这了,更多相关C++ 截图截屏内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • c++ 封装一个截图服务

    首先是抓图服务: ICaptureHelper.h #pragma once #include <windows.h> #include <string> using std::string; class ICaptureHelper { public: virtual ~ICaptureHelper() {} virtual bool Init(const string& windowName) = 0; virtual bool Init(HWND hwnd) = 0;

  • C++实现屏幕截图功能

    本文实例为大家分享了C++实现全屏截图功能的具体代码,供大家参考,具体内容如下 最近维护的项目,在某些情况下,光有日志还不行,于是添加了截图功能,特定情况下,会自动截图,辅助分析,从而改进程序.以下是截图实现代码. void CDemoDlg::ScreenShot(void) { CWnd *pDesktop = GetDesktopWindow(); CDC *pdeskdc = pDesktop->GetDC(); CRect re; //获取窗口的大小 pDesktop->GetCli

  • C++实现屏幕截图

    上回分享了一个全屏截图的代码,保存为BMP,参考:C++实现屏幕截图(全屏截图) 实际使用的过程中我发现截图文件实在大,无奈又整成了PNG截图,现在分享出来. MakePNG.h //MakePNG.h #pragma once #include <GdiPlus.h> using namespace Gdiplus; #pragma comment(lib,"GdiPlus.lib") class CMakePNG { public: CMakePNG(void); ~C

  • C++实现功能齐全的屏幕截图示例(附demo)

    目录 1.概述 2.屏幕截图的主要功能点 3.屏幕截图的主体实现思路 3.1.截图主窗口全屏置顶 3.2.桌面灰化 3.3.窗口自动套索 3.4.区域放大 3.5.截取区域的选择 3.5.截图工具条 3.6.矩形等图元的绘制 4.桌面灰化的实现细节 5.窗口自动套索实现 6.区域放大实现 7.截取区域的选择 8.矩形等图元的绘制 9.截图窗口的绘制机制 10.截图退出类型的详细设计 11.创建位图时将CreateCompatibleBitmap替换成CreateDIBSection 12.最后

  • C++ 使用PrintWindow实现窗口截图功能

    本文使用C++双缓存进行指定窗口截图.CreateDIBSection创建应用程序可以直接写入的.与设备无关的位图(DIB),它提供内存中位图的指针,外部程序可以直接使用. 需要注意的是,PrintWindow方法能够抓取使用D3D渲染的窗口(例如Excel.Win10自带视频播放器),如果抓取普通窗口则会附带窗口阴影,可见窗口阴影是Windows使用D3D渲染出来的. 1.PrintCaptureHelper.h #pragma once #include <windows.h> #incl

  • VC++基于Dx实现的截图程序示例代码

    本文所述的程序示例为VC++图象特效的截图示例,需要DirectX 3.0以上版,代码中的GetScreen函数是本截图程序的关键.运行这个程序可用Esc键结束.代码中需要ddutil.h与ddutil.cpp文件,请自行下载添加.关于InitDDraw()函数,功能是初始化DirectDraw环境,创建换页链(主页面,一个后台缓冲区),以及创建一个定时器. 具体的功能代码如下: #include <windows.h> #include <windowsx.h> #include

  • C++实现截图截屏的示例代码

    目录 1.截图工具 1.1 键盘截图(PrtScn键) 1.2 win10自带截图(Win+Shift+S) 1.3 系统自带的截图小工具 1.4 ffmpeg 1.5 ScreenToGif 1.6 Chrome 2.C++.GDI 2.1 微软官方例子 2.2 C++.GDI.CImage 3.C++.OpenGL 4.C++.OpenCV 5.C++.QT 1.截图工具 1.1 键盘截图(PrtScn键) 如何使用Microsoft Windows操作系统中的Print Screen(打印

  • IOS 开发之ios视频截屏的实现代码

    IOS 开发之ios视频截屏的实现代码 现在好多视频截屏软件,这里提供一个IOS 视频截屏的方法,大家可以参考下, 实现代码: //截屏 static int i=0; -(IBAction)screenShot:(id)sender{ UIGraphicsBeginImageContextWithOptions(CGSizeMake(640, 960), YES, 0); [[self.window layer] renderInContext:UIGraphicsGetCurrentCont

  • C# wpf使用ffmpeg命令行实现录屏的示例代码

    目录 前言 一.主要步骤 1.使用 AllowsTransparency实现穿透框 2.获取音频设备名称 3.命令行启动ffmpeg 4.使用JobObject管理子进程 二.完整代码 三.效果预览 1.录制中 2.录制动态流程 总结 前言 上一章我们实现了截屏界面与功能,接下来可以在此基础上实现录屏功能,录屏采用ffmpeg命令行实现会方便一些,效果也是不错的,当然前提是要对Windows子进程的控制比较熟悉,做出来之后完全可以满足项目使用. 一.主要步骤 1.使用 AllowsTranspa

  • Java实现的简单网页截屏功能示例

    本文实例讲述了Java实现的简单网页截屏功能.分享给大家供大家参考,具体如下: package awtDemo; import java.awt.AWTException; import java.awt.Desktop; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.awt.Robot; import java.

  • 让编辑器支持word复制黏贴、截屏的js代码

    chrome有很多人性化的API,比如拖拽, 比如图片可以转化为base64等: 比如知乎上面的回复中可以直接黏贴图片,  就不需要手动点击图片上传按钮, 选择图片, 确认上传等等: 知乎参考地址:打开 让编辑器支持word的复制黏贴, 其中图片会转化为base64编码, 如果是通过远程打开这个静态页, 黏贴word文档的时候, 图片不会黏贴进来, 因为远程地址无法访问本地磁盘的绝对路径, 如果把下面代码保存成静态界面打开, 那么word中的图片都可以看见, 而且都会被转化为base64编码:

  • JS如何实现页面截屏功能实例代码

    "页面截屏"是前端经常遇到的需求,比如页面生成海报,弹窗图片分享等,因为浏览器没有原生的截图API,所以需要借助canvas来实现导出图片实现需求. 可行性方案 方案1: 将 DOM 改写成 canvas ,调用canvas的toBlob或者toDataURL方法即刻上传到七牛云或服务器 方案2: 使用第三方库html2canvas.js实现 canvas , 在不更改页面已有DOM的情况下优雅生产canvas 解决方案的选择 方案1:需要手动计算每个DOM元素的Computed St

  • android截屏功能实现代码

    android开发中通过View的getDrawingCache方法可以达到截屏的目的,只是缺少状态栏! 原始界面 截屏得到的图片 代码实现 1. 添加权限(AndroidManifest.xml文件里) 复制代码 代码如下: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 2. 添加1个Button(activity_main.xml文件) <RelativeL

  • iOS屏幕旋转与锁屏的示例代码

    在做视频开发时遇到屏幕旋转问题,其中涉及到 StatusBar. UINavigationController.UITabBarController .UIViewcontroller . 在设备锁屏下的整体效果图 iOS-旋转.gif 主要涉及以下4点: 横竖屏的旋转 屏幕旋转相应改变视图位置 旋转时状态栏的隐藏与显示 锁屏 1.横竖屏旋转 第1步: -(UIInterfaceOrientationMask)application:(UIApplication *)application su

  • Android源码解析之截屏事件流程

    今天这篇文章我们主要讲一下Android系统中的截屏事件处理流程.用过android系统手机的同学应该都知道,一般的android手机按下音量减少键和电源按键就会触发截屏事件(国内定制机做个修改的这里就不做考虑了).那么这里的截屏事件是如何触发的呢?触发之后android系统是如何实现截屏操作的呢?带着这两个问题,开始我们的源码阅读流程. 我们知道这里的截屏事件是通过我们的按键操作触发的,所以这里就需要我们从android系统的按键触发模块开始看起,由于我们在不同的App页面,操作音量减少键和电

  • Android实现截屏与截长图功能

    本文实例为大家分享了Android实现截屏与截长图功能展示的具体代码,供大家参考,具体内容如下 Demo在GitHub的地址:ScreenShoot Demo在CSDN上的下载地址:Android实现截屏与截长图功能 在Android开发中,有时候会遇到需要截屏分享到朋友圈或者QQ,截屏有截取当前屏幕,也有需要截取不仅一个屏幕,可能会很长. 截取当前屏幕并保存到内存卡的方法: // 获取指定Activity的截屏,保存到png文件 public static Bitmap takeScreenS

随机推荐