前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >WPF截屏实现

WPF截屏实现

作者头像
码客说
发布2021-07-12 11:41:58
1.2K0
发布2021-07-12 11:41:58
举报
文章被收录于专栏:码客

前言

使用C#直接截屏的话有两个问题

  • 截图效率不高
  • 内存释放不及时,如果间隔时间较短进行截屏,就会导致内存占用不断上升最终程序崩溃

为了解决这个问题这里就采用了利用nircmd.exe截屏,但是这个工具截屏不能设置截屏后的大小,所以我们在做一下压缩并删除之前文件就行了。

正文

使用nircmd.exe截屏

官网:http://www.nirsoft.net/utils/nircmd.html

链接:https://pan.baidu.com/s/1AyGNHN5XM5v08gjGx3y6Dw 提取码:sytu

代码语言:javascript
复制
nircmd.exe savescreenshot "d:\temp.png"

这种方法其实各种语言都可以使用。

首先在项目下放入下载的exe路径:Tools/nircmd.exe

项目右键=>属性=>生成事件=>生成前事件命令行 添加如下

代码语言:javascript
复制
xcopy /Y /i /e $(ProjectDir)\Tools $(TargetDir)\Tools

目的是为了打包运行时能够找到 nircmd.exe

工具类

代码语言:javascript
复制
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace SchoolClient.Utils
{
    internal class ZScreenUtil2
    {
        public static bool CaptureScreenSave(string filePath)
        {
            int lastindex = filePath.LastIndexOf(Path.DirectorySeparatorChar);
            if (lastindex < filePath.Length)
            {
                string fileFolder = filePath.Substring(0, lastindex);
                string filename = filePath.Substring(lastindex + 1);
                string tempFilePath = fileFolder + Path.DirectorySeparatorChar + "_temp_" + filename;

                string basePath = AppDomain.CurrentDomain.BaseDirectory;
                string toolsPath = System.IO.Path.Combine(basePath, "Tools");

                Process mps = new Process();
                ProcessStartInfo mpsi = new ProcessStartInfo("nircmd.exe", "savescreenshot \"" + tempFilePath+"\"" )
                {
                    WorkingDirectory = toolsPath,
                    UseShellExecute = true,
                    RedirectStandardInput = false,
                    RedirectStandardOutput = false,
                    CreateNoWindow = true,
                    WindowStyle = ProcessWindowStyle.Hidden
                };
                mps.StartInfo = mpsi;
                mps.Start();
                mps.WaitForExit();
                mps.Close();

                bool result = GetPicThumbnail(tempFilePath, filePath, 1920, 1080, 80, true);
                return result;
            }
            else
            {
                return false;
            }
        }

        /// 无损压缩图片
        /// <param name="sFile">原图片</param>
        /// <param name="dFile">压缩后保存位置</param>
        /// <param name="dWidth"></param>
        /// <param name="dHeight">高度</param>
        /// <param name="ratio">压缩质量(数字越小压缩率越高) 1-100</param>
        /// <returns></returns>
        public static bool GetPicThumbnail(string sFile, string dFile, int dWidth, int dHeight, int ratio, bool deleteSFile)
        {
            System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
            ImageFormat tFormat = iSource.RawFormat;

            //按比例缩放
            Size tem_size = new Size(iSource.Width, iSource.Height);
            int sW;
            int sH;
            if (tem_size.Width > dHeight || tem_size.Width > dWidth)
            {
                if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
                {
                    sW = dWidth;
                    sH = (dWidth * tem_size.Height) / tem_size.Width;
                }
                else
                {
                    sH = dHeight;
                    sW = (tem_size.Width * dHeight) / tem_size.Height;
                }
            }
            else
            {
                sW = tem_size.Width;
                sH = tem_size.Height;
            }

            Bitmap ob = new Bitmap(dWidth, dHeight);
            Graphics g = Graphics.FromImage(ob);

            g.Clear(Color.WhiteSmoke);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(
                    iSource,
                    new Rectangle((dWidth - sW) / 2,(dHeight - sH) / 2, sW, sH),
                    0,
                    0,
                    iSource.Width,
                    iSource.Height,
                    GraphicsUnit.Pixel
                );

            g.Dispose();
            //以下代码为保存图片时,设置压缩质量
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = ratio;//设置压缩的比例1-100
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;
            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
                }
                else
                {
                    ob.Save(dFile, tFormat);
                }
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                iSource.Dispose();
                ob.Dispose();

                if (deleteSFile)
                {
                    FileInfo di = new FileInfo(sFile);
                    if (di.Exists)
                    {
                        try
                        {
                            di.Delete();
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }
        }
    }
}

注意在压缩图片前一定要调用

代码语言:javascript
复制
mps.WaitForExit();
mps.Close();

这样才会在生成图片后进行压缩。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-07-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 正文
相关产品与服务
文件存储
文件存储(Cloud File Storage,CFS)为您提供安全可靠、可扩展的共享文件存储服务。文件存储可与腾讯云服务器、容器服务、批量计算等服务搭配使用,为多个计算节点提供容量和性能可弹性扩展的高性能共享存储。腾讯云文件存储的管理界面简单、易使用,可实现对现有应用的无缝集成;按实际用量付费,为您节约成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档