Search code examples
c#opencvavaloniauiavalonia

Is it possible to create Avalonia.Media.Imaging.Bitmap from System.Drawing.Bitmap?


I am writing an application in Avalonia and using OpenCvSharp to get frames from the camera. This worked with WPF - there I just called

Image.Source = Mat.ToBitmapSource();

but this doesn't work in Avalonia, because there is a different type of Image control, and a different type of its Source property.

I tried doing this via a MemoryStream, but then the Bitmap constructor crashes with an ArgumentNullException (although the stream is not null).


Solution

  • Of course, as soon as I asked you that, I found a solution. Load the image into memory and then call it back.

    I was getting the same type of error but that was fixed after I implemented the using statement.

    //Place this in your class to create a class variable and create the System.Drawing.Bitmap Bitmap 
    private System.Drawing.Bitmap irBitmap = new System.Drawing.Bitmap(256, 192, PixelFormat.Format24bppRgb);
    
    //Add this using statement to the function you're converting inside of 
    //to convert the System.Drawing.Bitmap to Avalonia compatible image for view/viewmodel
    
    using (MemoryStream memory = new MemoryStream())
                {
                    irBitmap.Save(memory, ImageFormat.Png);
                    memory.Position = 0;
    
                    //AvIrBitmap is our new Avalonia compatible image. You can pass this to your view
                    Avalonia.Media.Imaging.Bitmap AvIrBitmap = new Avalonia.Media.Imaging.Bitmap(memory);
                 }
    

    Let me know if you have questions or how to specifically tie this into your app. There wasn't a lot of code provided earlier so I didn't have any idea what to name variables for your specific use case.