Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a byte array from a redirected process

I am using the process object in c#

I am also using FFMPEG.

I am trying to read the bytes from the redirected output. i know the data is an image but when I use the following code I do not get an image byte array.

this is my code:

var process = new Process();
process.StartInfo.FileName = @"C:\bin\ffmpeg.exe";
process.StartInfo.Arguments = @" -i rtsp://admin:[email protected]: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);

The 1st bytes are not the header of a jpeg?

like image 221
Andrew Simpson Avatar asked Mar 17 '23 00:03

Andrew Simpson


1 Answers

I think treating the output as a text stream is not the right thing to do here. Something like this worked for me, just directly read the data off the output pipe, it doesn't need conversion.

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();
like image 160
steve16351 Avatar answered Mar 28 '23 20:03

steve16351