Search code examples
c#wpfimage-processingbitmapimagesource

Fast conversion of Bitmap to ImageSource


I'm programming in WPF(c#) for image processing purpose. What is fastet way for converting Bitmap to ImageSource?


Solution

  • Try converting it to a BitmapImage first:

    public BitmapImage ConvertBitmap(System.Drawing.Bitmap bitmap)
        {         
            MemoryStream ms = new MemoryStream();
            bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            BitmapImage image = new BitmapImage();
            image.BeginInit();
            ms.Seek(0, SeekOrigin.Begin);
            image.StreamSource = ms;
            image.EndInit();
    
            return image;
        }
    

    Then:

    public void MyMethod(System.Drawing.Bitmap myBitmap)
    {
        var myImage = new Image();
        myImage.Source = ConvertBitmap(myBitmap);
    }
    

    You didn't explain where the Bitmap was coming from so I had to leave that part out.