从重定向的进程中读取一个字节数组

5

我正在使用c#中的process对象。

我也在使用FFMPEG。

我正在尝试从重定向的输出中读取字节。我知道这些数据是图像,但是当我使用以下代码时,我无法获得图像字节数组。

这是我的代码:

var process = new Process();
process.StartInfo.FileName = @"C:\bin\ffmpeg.exe";
process.StartInfo.Arguments = @" -i rtsp://admin:admin@192.168.0.8:554/video_1 -an -f image2 -s 360x240 -vframes 1 -";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.Start();
var output = process.StandardOutput.ReadToEnd();
byte[] bytes = Encoding.ASCII.GetBytes(output);

第一个字节不是jpeg的标头吗?
1个回答

8

我认为将输出视为文本流并不是在这里做正确的事情。对我来说,像这样做可以奏效,只需直接从输出管道中读取数据,无需转换。

var process = new Process();
process.StartInfo.FileName = @"C:\bin\ffmpeg.exe";
// take frame at 17 seconds
process.StartInfo.Arguments = @" -i c:\temp\input.mp4 -an -f image2 -vframes 1 -ss 00:00:17 pipe:1";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.Start();

FileStream baseStream = process.StandardOutput.BaseStream as FileStream;
byte[] imageBytes = null;
int lastRead = 0;

using (MemoryStream ms = new MemoryStream())
{            
    byte[] buffer = new byte[4096];
    do
    {
        lastRead = baseStream.Read(buffer, 0, buffer.Length);
        ms.Write(buffer, 0, lastRead);
    } while (lastRead > 0);

    imageBytes = ms.ToArray();
}

using (FileStream s = new FileStream(@"c:\temp\singleFrame.jpeg", FileMode.Create))
{
    s.Write(imageBytes, 0, imageBytes.Length);
}

Console.ReadKey();

为什么是4096?我可以使用更大的缓冲区吗? - Srdjan M.
是的,你可以在合理范围内使用不同的尺寸。 - steve16351

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接