C#使用GifBitmapEncoder录制屏幕为gif图

前言

该文章将会实现录制全屏、选取区域最终转为Gif图


二、使用步骤

1.引入程序集

PresentationCore
WindowsBase

2.引入类

ScreenshotForm通过右侧超链接查看
ScreenHelper通过右侧超链接查看

3.创建方法

		/// <summary>
        /// 压缩图片质量
        /// </summary>
        /// <param name="ImageBefore">压缩前图片</param>
        /// <param name="quality">质量</param>
        /// <returns></returns>
        public static System.IO.MemoryStream CompressImageStream(Image ImageBefore, long quality)
        {
            System.Drawing.Imaging.ImageCodecInfo myEncoder = GetEncoder("image/jpeg");
            System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
            encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            var memoryStream = new System.IO.MemoryStream();
            ImageBefore.Save(memoryStream, myEncoder, encoderParameters);
            return memoryStream;
        }
        
		/// <summary>
        /// 压缩图片质量
        /// </summary>
        /// <param name="ImageBefore">压缩前图片</param>
        /// <param name="quality">质量</param>
        /// <returns></returns>
        public static Image CompressImage(Image ImageBefore, long quality)
        {
            var stream = CompressImageStream(ImageBefore, quality);
            return Image.FromStream(stream);
        }

        /// <summary>
        /// 通过mimeType(和ContentType差不多)获取 ImageCodecInfo
        /// </summary>
        /// <param name="mimeType">媒体类型(和ContentType差不多)</param>
        /// <returns>ImageCodecInfo</returns>
        public static System.Drawing.Imaging.ImageCodecInfo GetEncoder(string mimeType)
        {
            System.Drawing.Imaging.ImageCodecInfo[] encoders = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
            for (int i = 0; i < encoders.Length; i++)
            {
                if (encoders[i].MimeType == mimeType)
                {
                    return encoders[i];
                }
            }
            return null;
        }

4.录屏代码类

代码如下:

	/// <summary>
    /// 录屏
    /// </summary>
    public class ScreenRecording
    {
        /// <summary>
        /// 实例化
        /// </summary>
        /// <param name="IsLoop">是否将Gif图设置为循环播放</param>
        public ScreenRecording(bool IsLoop = true)
        {
            this.IsLoop = IsLoop;
        }

        /// <summary>
        /// 是否正在录屏
        /// </summary>
        public bool IsRecording { get; private set; }

        /// <summary>
        /// 是否将Gif图设置为循环播放
        /// </summary>
        public bool IsLoop { get; set; }

        /// <summary>
        /// 录屏线程
        /// </summary>
        Task task { get; set; }

        #region Gif操作
        /// <summary>
        /// 录制Gif图片
        /// </summary>
        /// <param name="flieName">保存路径</param>
        /// <param name="quality">质量(≤0不生效)</param>
        /// <param name="timeout">每过多少毫秒生成一帧图片</param>
        /// <param name="EndAction">gif图生成完成后回调</param>
        /// <returns>是否成功启动录屏</returns>
        public bool StartRecordingGif(string flieName, long quality = -1, int timeout = 200, Action EndAction = null)
        {
            return StartRecordingGif(flieName, quality, timeout, EndAction, ScreenHelper.CopyScreenToImage);
        }

        /// <summary>
        /// 选取区域录制Gif图片
        /// </summary>
        /// <param name="flieName">保存路径</param>
        /// <param name="quality">质量(≤0不生效)</param>
        /// <param name="timeout">每过多少毫秒生成一帧图片</param>
        /// <param name="EndAction">gif图生成完成后回调</param>
        /// <returns>是否成功启动录屏</returns>
        public bool StartRecordingGifScreen(string flieName, long quality = -1, int timeout = 200, Action EndAction = null)
        {
            bool IsRecording = false;
            ScreenshotForm screenshotForm = new ScreenshotForm();
            screenshotForm.ClickSuccessEvent += () =>
            {
                if (screenshotForm.Bitmap == null)
                {
                    return;
                }
                IsRecording = StartRecordingGif(flieName, quality, timeout, EndAction,
                    () => ScreenHelper.CopyScreenToImage(screenshotForm.UpperLeftSource, screenshotForm.Bitmap.Size));
            };
            screenshotForm.ShowDialog();
            return IsRecording;
        }
        /// <summary>
        /// 录制Gif图片
        /// </summary>
        /// <param name="flieName">保存路径</param>
        /// <param name="quality">质量(≤0不生效)</param>
        /// <param name="timeout">每过多少毫秒生成一帧图片</param>
        /// <param name="EndAction">gif图生成完成后回调</param>
        /// <param name="ImageFunc">如何产生图像</param>
        /// <returns>是否成功启动录屏</returns>
        public bool StartRecordingGif(string flieName, long quality, int timeout, Action EndAction, Func<System.Drawing.Bitmap> ImageFunc)
        {
            if (IsRecording)
            {
                return false;
            }
            IsRecording = true;
            task = Task.Run(() =>
            {
                var Gif = new System.Windows.Media.Imaging.GifBitmapEncoder();
                while (IsRecording)
                {
                    System.Threading.Thread.Sleep(timeout);
                    if (!IsRecording)
                    {
                        break;
                    }
                    var img = ImageFunc();
                    if (quality > 0)
                    {
                        img = (Bitmap)CompressImage(img, quality);
                    }
                    var bmp = img.GetHbitmap();
                    var src = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                        bmp,
                        IntPtr.Zero,
                        System.Windows.Int32Rect.Empty,
                        System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                    Gif.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(src));
                }
                if (this.IsLoop)
                {
                    using (var ms = new MemoryStream())
                    {
                        Gif.Save(ms);
                        var fileBytes = ms.ToArray();
                        var applicationExtension = new byte[] { 33, 255, 11, 78, 69, 84, 83, 67, 65, 80, 69, 50, 46, 48, 3, 1, 0, 0, 0 };
                        var newBytes = new List<byte>();
                        newBytes.AddRange(fileBytes.Take(13));
                        newBytes.AddRange(applicationExtension);
                        newBytes.AddRange(fileBytes.Skip(13));
                        File.WriteAllBytes(flieName, newBytes.ToArray());
                    }
                }
                else
                {
                    using (FileStream fs = new FileStream(flieName, FileMode.Create))
                    {
                        Gif.Save(fs);
                    }
                }

                if (EndAction != null)
                {
                    EndAction();
                }
                task = null;
            });
            return true;
        }

        /// <summary>
        /// 停止录制Gif
        /// </summary>
        /// <param name="IsWait">是否强制等待Gif生成完毕</param>
        public void StopRecordingGif(bool IsWait = false)
        {
            IsRecording = false;
            if (task != null && IsWait)
            {
                task.Wait();
            }
        }
        #endregion
    }

4.踩坑记录

  • System.Windows.Media.Imaging.GifBitmapEncoder这个类在使用过程中要在同一线程中(创建、使用)否则会报错
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值