kekyo / FlashCap

Independent video frame capture library on .NET/.NET Core and .NET Framework.
Apache License 2.0
203 stars 29 forks source link

A generic error occurred in GDI+ when process MJPEG on Winforms #67

Closed AndyInside closed 7 months ago

AndyInside commented 1 year ago

Exception thrown: 'System.Runtime.InteropServices.ExternalException' in System.Drawing.Common.dll System.Runtime.InteropServices.ExternalException (0x80004005): A generic error occurred in GDI+. at System.Drawing.Image.ValidateImage(IntPtr image) at System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement, Boolean validateImageData) at System.Drawing.Image.FromStream(Stream stream) at FlashCap.WindowsForms.MainForm.OnPixelBufferArrived(PixelBufferScope bufferScope) in C:\temp\FlashCap-main\FlashCap-main\samples\FlashCap.WindowsForms\MainForm.cs:line 93 at FlashCap.FrameProcessors.DelegatedQueuingProcessor.ThreadEntry() in C:\temp\FlashCap-main\FlashCap-main\FlashCap.Core\FrameProcessors\QueuingProcessor.cs:line 159

kekyo commented 1 year ago

@AndyInside I think I have seen this problem before. In Windows Forms, when Image.FromStream() is executed in a worker thread, it throws an exception. I have not been able to reproduce this behavior in my environment, and again. The true reason is unknown... However, since this is the second time this has happened, I decided to revise the sample code.

In 9fce01cb1b747e1a9f7f8603c9cdf751c6c7dae6 with the modification, I used CopyImage() in the worker thread to copy the image once to an array, and Image.FromStream() is executed on the UI thread.

Does this fix work? If it works, I will merge it and reflect it.

AndyInside commented 1 year ago

thanks!!! by the way your sample code works nice on WPF but not on Winforms

AndyInside commented 1 year ago

checked, no the same thing... when i try to save frame to file, it can't be opened with paint or windows preview, but opened well with advanced viewers. something wrong with file content, something wrong with palette, because frame loads to Image with disabled validation (validateImageData) but when loaded property palette expose Exception. maybe it will helps you thanks!

AndyInside commented 1 year ago

also when i capture in BMP format all is working fine! problem with MJPEG

kekyo commented 1 year ago

It may not be a fundamental solution, but if it's an MJPEG issue and the goal is to save it to a file, saving it using SkiaSharp may fix it.

There may be a problem with GDI+'s implementation of JPEG, I have previously seen such a problem, though not with FlashCap's sample code.