当前位置:实例文章 » C#开发实例» [文章]基于.NetCore开源的Windows的GIF录屏工具

基于.NetCore开源的Windows的GIF录屏工具

发布人:shili8 发布时间:2023-06-27 12:47 阅读次数:155

近年来,随着互联网的发展,GIF动图已经成为了网络上非常流行的一种表现形式。而在制作GIF动图的过程中,录屏工具是必不可少的一种工具。本文将介绍一款基于.NetCore开源的Windows的GIF录屏工具,同时提供部分代码示例和代码注释。

1. 环境准备

首先,我们需要安装.NetCore SDK,以便于编译和运行我们的代码。可以在官网上下载对应的版本进行安装。

2. 项目创建

在Visual Studio中创建一个新的控制台应用程序,命名为GIFRecorder。在项目中添加以下NuGet包:

- Microsoft.Extensions.Configuration
- Microsoft.Extensions.Configuration.Json
- Microsoft.Extensions.DependencyInjection
- Microsoft.Extensions.Logging
- Microsoft.Extensions.Logging.Console
- Microsoft.Extensions.Logging.Debug

3. 配置文件

在项目根目录下创建appsettings.json文件,用于存储配置信息。示例配置如下:

{
GIFRecorder: {
FrameRate: 10
Quality: 50
OutputPath: C:UsersAdministratorDesktopoutput.gif
}
}

4. 代码实现

首先,我们需要定义一个接口,用于定义录屏的行为:

public interface IRecorder
{
void Start();
void Stop();
}

然后,我们实现这个接口:

public class GIFRecorder : IRecorder
{
private readonly ILogger _logger;
private readonly IConfiguration _configuration;
private readonly ScreenCapture _screenCapture;
private readonly GifEncoder _gifEncoder;
private readonly string _outputPath;
private readonly int _frameRate;
private readonly int _quality;
private CancellationTokenSource _cancellationTokenSource;

public GIFRecorder(ILogger logger IConfiguration configuration)
{
_logger = logger;
_configuration = configuration;
_screenCapture = new ScreenCapture();
_gifEncoder = new GifEncoder();
_outputPath = _configuration[GIFRecorder:OutputPath];
_frameRate = int.Parse(_configuration[GIFRecorder:FrameRate]);
_quality = int.Parse(_configuration[GIFRecorder:Quality]);
}

public void Start()
{
_cancellationTokenSource = new CancellationTokenSource();
Task.Run(() => Record(_cancellationTokenSource.Token));
}

public void Stop()
{
_cancellationTokenSource.Cancel();
}

private async Task Record(CancellationToken cancellationToken)
{
_logger.LogInformation(Recording started.);

using (var stream = new FileStream(_outputPath FileMode.Create))
{
_gifEncoder.Start(stream);
var interval = TimeSpan.FromSeconds(1.0 / _frameRate);

while (!cancellationToken.IsCancellationRequested)
{
var bitmap = _screenCapture.Capture();
_gifEncoder.AddFrame(bitmap interval);
await Task.Delay(interval cancellationToken);
}

_gifEncoder.Finish();
}

_logger.LogInformation(Recording stopped.);
}
}

在构造函数中,我们使用依赖注入的方式获取ILogger和IConfiguration实例,并初始化ScreenCapture和GifEncoder实例。然后,我们从配置文件中获取录屏的相关配置信息。在Start方法中,我们启动一个新的线程来执行Record方法。在Record方法中,我们不断地截取屏幕并将截图添加到GIF动图中,直到用户停止录屏。

5. 屏幕截取

我们使用ScreenCapture类来截取屏幕。这个类的实现如下:

public class ScreenCapture
{
public Bitmap Capture()
{
var screenBounds = Screen.PrimaryScreen.Bounds;
var bitmap = new Bitmap(screenBounds.Width screenBounds.Height);

using (var graphics = Graphics.FromImage(bitmap))
{
graphics.CopyFromScreen(screenBounds.X screenBounds.Y 0 0 screenBounds.Size);
}

return bitmap;
}
}

在Capture方法中,我们获取主屏幕的大小,并创建一个与主屏幕大小相同的Bitmap对象。然后,我们使用Graphics对象将屏幕截图复制到Bitmap对象中。

6. GIF编码

我们使用GifEncoder类来将截图添加到GIF动图中。这个类的实现如下:

public class GifEncoder
{
private readonly List _frames;
private readonly List _delays;

public GifEncoder()
{
_frames = new List();
_delays = new List();
}

public void Start(Stream stream)
{
var encoder = new GifBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(_frames[0]));
encoder.Save(stream);
}

public void AddFrame(Bitmap bitmap TimeSpan delay)
{
_frames.Add(bitmap);
_delays.Add(delay);
}

public void Finish()
{
var encoder = new GifBitmapEncoder();

for (var i = 0; i < _frames.Count; i++)
{
var frame = BitmapFrame.Create(_frames[i]);
var metadata = new BitmapMetadata(gif);
metadata.SetQuery(/grctlext/Delay (ushort)(_delays[i].TotalMilliseconds / 10));
frame.Metadata = metadata;
encoder.Frames.Add(frame);
}

using (var stream = new FileStream(output.gif FileMode.Create))
{
encoder.Save(stream);
}
}
}

在构造函数中,我们初始化_frames和_delays列表。在Start方法中,我们将第一帧截图保存到GIF动图中。在AddFrame方法中,我们将新的截图和时间间隔添加到列表中。在Finish方法中,我们使用GifBitmapEncoder类将所有的截图和时间间隔保存到GIF动图中。

7. 使用示例

在Main方法中,我们使用依赖注入的方式获取IRecorder实例,并调用Start和Stop方法来开始和停止录屏。示例代码如下:

static void Main(string[] args)
{
var serviceProvider = new ServiceCollection()
.AddLogging(builder => builder.AddConsole().AddDebug())
.AddSingleton(new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(appsettings.json optional: true reloadOnChange: true)
.Build())
.AddSingleton()
.BuildServiceProvider();

var recorder = serviceProvider.GetService();
recorder.Start();
Console.ReadKey();
recorder.Stop();
}

8. 总结

本文介绍了一款基于.NetCore开源的Windows的GIF录屏工具,同时提供了部分代码示例和代码注释。通过本文的学习,读者可以了解到如何使用.NetCore开发Windows应用程序,并掌握录屏和GIF编码的相关知识。

相关标签:.netcore开源windows
其他信息

其他资源

Top