简体   繁体   English

使用C#从静止图像创建MJPEG视频

[英]Creating an MJPEG video from still images using C#

I am trying to create a timelapse from JPEG images. 我正在尝试从JPEG图像创建游戏中时光倒流。 I've read that the structure of M-JPEG is fairly simple, essentially just concatenated JPEG images that most browsers can play. 我读过M-JPEG的结构相当简单,实际上只是大多数浏览器可以播放的级联JPEG图像。

var result = new List<byte>();
var converter = new ImageConverter();

foreach (var file in Directory.GetFiles(srcFolder, "*.jpg", SearchOption.TopDirectoryOnly)) {
      using (var image = Image.FromFile(file) as Bitmap) {
          var bytes = converter.ConvertTo(image, typeof(byte[])) as byte[];
          result.AddRange(bytes);
          image.Dispose();
      }
}

File.WriteAllBytes($"{destFolder}video.mjpeg", result.ToArray());

However, it does not work. 但是,它不起作用。 The resulting video cannot be played by any browser. 最终的视频无法通过任何浏览器播放。 It can be played in VLC, showing the correct first image, but then does not change to any proceeding image in its ten second duration. 它可以在VLC中播放,显示正确的第一张图像,但是在其十秒钟的持续时间内不会更改为任何进行中的图像。

Can someone say what I'm doing wrong? 有人可以说我做错了吗? Also, is it possible to adjust the frame rate via headers? 另外,是否可以通过标题调整帧速率?

Update: Thanks to the suggestions, I got it working properly in VLC. 更新:由于建议,我使它在VLC中可以正常工作。 Still does not play in browsers, but it is at least step in the right direction. 仍然无法在浏览器中播放,但这至少是朝正确方向迈出的一步。

var result = new List<byte>();
var converter = new ImageConverter();

var header = "HTTP/1.1 200 OK\r\n" +
             "Content-Type: multipart/x-mixed-replace; boundary=" +
             "--boundary" +
             "\r\n";
result.AddRange(Encoding.ASCII.GetBytes(header));

foreach (var file in Directory.GetFiles(srcFolder, "*.jpg", SearchOption.TopDirectoryOnly)) {
    using (var image = Image.FromFile(file) as Bitmap) {
        var bytes = converter.ConvertTo(image, typeof(byte[])) as byte[];

        StringBuilder sb = new StringBuilder();

        sb.AppendLine();
        sb.AppendLine("--boundary");
        sb.AppendLine("Content-Type: image/jpeg");
        sb.AppendLine("Content-Length: " + image.Size.ToString());
        sb.AppendLine();
        result.AddRange(Encoding.ASCII.GetBytes(sb.ToString()));
        result.AddRange(bytes);
        result.AddRange(Encoding.ASCII.GetBytes("\r\n"));
        image.Dispose();
    }
}

File.WriteAllBytes($"{destFolder}hat.mjpeg", result.ToArray());

Checking Google, found this: 检查谷歌,发现:

https://www.codeproject.com/Articles/371955/Motion-JPEG-Streaming-Server https://www.codeproject.com/Articles/371955/Motion-JPEG-Streaming-Server

This article is about streaming, but I believe it may help you with your project. 本文是关于流媒体的,但我相信它可能会对您的项目有所帮助。 There is a downloadable code example. 有一个可下载的代码示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM