How to use BitmapToByteArray method of FlaUI.Core.Capturing.VideoRecorder class

Best FlaUI code snippet using FlaUI.Core.Capturing.VideoRecorder.BitmapToByteArray

VideoRecorder.cs

Source:VideoRecorder.cs Github

copy

Full Screen

...74 using (var img = _captureMethod(this))75 {76 var image = new ImageData77 {78 Data = BitmapToByteArray(img.Bitmap),79 Width = img.Bitmap.Width,80 Height = img.Bitmap.Height81 };82 _frames.Add(image);83 ++frameCount;84 }85 var timeTillNextFrame = timestamp + frameInterval - DateTime.UtcNow;86 if (timeTillNextFrame > TimeSpan.Zero)87 {88 await Task.Delay(timeTillNextFrame);89 }90 }91 if (totalMissedFrames > 0)92 {93 Logger.Default.Warn($"Totally added {totalMissedFrames} missing frame(s) to \"{Path.GetFileName(TargetVideoPath)}\".");94 }95 }96 private void WriteLoop()97 {98 var videoPipeName = $"flaui-capture-{Guid.NewGuid()}";99 var ffmpegIn = new NamedPipeServerStream(videoPipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 10000, 10000);100 const string pipePrefix = @"\\.\pipe\";101 Process ffmpegProcess = null;102 var isFirstFrame = true;103 ImageData lastImage = null;104 while (!_frames.IsCompleted)105 {106 _frames.TryTake(out var img, -1);107 if (img == null)108 {109 // Happens when the queue is marked as completed110 continue;111 }112 if (isFirstFrame)113 {114 isFirstFrame = false;115 Directory.CreateDirectory(new FileInfo(TargetVideoPath).Directory.FullName);116 var videoInFormat = _settings.UseCompressedImages ? "" : "-f rawvideo"; // Used when sending raw bitmaps to the pipe117 var videoInArgs = $"-framerate {_settings.FrameRate} {videoInFormat} -pix_fmt rgb32 -video_size {img.Width}x{img.Height} -i {pipePrefix}{videoPipeName}";118 var videouOutCodec = _settings.VideoFormat == VideoFormat.x264119 ? $"-c:v libx264 -crf {_settings.VideoQuality} -pix_fmt yuv420p -preset ultrafast"120 : $"-c:v libxvid -qscale:v {_settings.VideoQuality}";121 var videoOutArgs = $"{videouOutCodec} -r {_settings.FrameRate} -vf \"scale={img.Width.Even()}:{img.Height.Even()}\"";122 ffmpegProcess = StartFFMpeg(_settings.ffmpegPath, $"-y -hide_banner -loglevel warning {videoInArgs} {videoOutArgs} \"{TargetVideoPath}\"");123 ffmpegIn.WaitForConnection();124 }125 if (img.IsRepeatFrame)126 {127 // Repeat the last frame128 ffmpegIn.WriteAsync(lastImage.Data, 0, lastImage.Data.Length);129 }130 else131 {132 // Write the received frame and save it as last image133 ffmpegIn.WriteAsync(img.Data, 0, img.Data.Length);134 if (lastImage != null)135 {136 lastImage.Dispose();137 lastImage = null;138 GC.Collect();139 }140 lastImage = img;141 }142 }143 ffmpegIn.Flush();144 ffmpegIn.Close();145 ffmpegIn.Dispose();146 ffmpegProcess?.WaitForExit();147 }148 /// <summary>149 /// Starts recording.150 /// </summary>151 private void Start()152 {153 _shouldRecord = true;154 _recordStartTime = DateTime.UtcNow;155 _recordTask = Task.Factory.StartNew(async () => await RecordLoop(), TaskCreationOptions.LongRunning);156 _writeTask = Task.Factory.StartNew(WriteLoop, TaskCreationOptions.LongRunning);157 }158 /// <summary>159 /// Stops recording and finishes the video file.160 /// </summary>161 public void Stop()162 {163 if (_recordTask != null)164 {165 _shouldRecord = false;166 _recordTask.Wait();167 _recordTask = null;168 }169 _frames.CompleteAdding();170 if (_writeTask != null)171 {172 try173 {174 _writeTask.Wait();175 _writeTask = null;176 }177 catch (Exception ex)178 {179 Logger.Default.Warn(ex.Message, ex);180 }181 }182 }183 public void Dispose()184 {185 Stop();186 }187 private Process StartFFMpeg(string exePath, string arguments)188 {189 var process = new Process190 {191 StartInfo =192 {193 FileName = exePath,194 Arguments = arguments,195 UseShellExecute = false,196 CreateNoWindow = true,197 RedirectStandardError = true,198 RedirectStandardInput = true,199 RedirectStandardOutput = true,200 },201 EnableRaisingEvents = true202 };203 process.OutputDataReceived += OnProcessDataReceived;204 process.ErrorDataReceived += OnProcessDataReceived;205 process.Start();206 if (_settings.EncodeWithLowPriority)207 {208 process.PriorityClass = ProcessPriorityClass.BelowNormal;209 }210 process.BeginErrorReadLine();211 return process;212 }213 private void OnProcessDataReceived(object s, DataReceivedEventArgs e)214 {215 if (!String.IsNullOrWhiteSpace(e.Data))216 {217 Logger.Default.Info(e.Data);218 }219 }220 private byte[] BitmapToByteArray(Bitmap bitmap)221 {222 using (var stream = new MemoryStream())223 {224 bitmap.Save(stream, _settings.UseCompressedImages ? ImageFormat.Png : ImageFormat.Bmp);225 return stream.ToArray();226 }227 // Previous way228 BitmapData bmpdata = null;229 try230 {231 bmpdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);232 var numbytes = Math.Abs(bmpdata.Stride) * bitmap.Height;233 var bytedata = new byte[numbytes];234 var ptr = bmpdata.Scan0;...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run FlaUI automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful