C#: Convert an Image to a BitmapImage

How to convert a System.Drawing.Image to a System.Windows.Media.Imaging.BitmapImage.

using System.Windows.Media.Imaging;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

//...

public BitmapImage Convert(Image img)
{
    using (var memory = new MemoryStream())
    {
        img.Save(memory, ImageFormat.Png);
        memory.Position = 0;

        var bitmapImage = new BitmapImage();
        bitmapImage.BeginInit();
        bitmapImage.StreamSource = memory;
        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapImage.EndInit();

        return bitmapImage;
    }
}

This and other approaches to solving this problem can be found on this StackOverflow page.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.