Question

I get this error. Here is the code:

    Image image;
    BitmapImage BmpImg;
    MemoryStream ms;

    public void Convert()
    {
        ms = new MemoryStream();
        image.Save(ms, ImageFormat.Jpeg);

        BmpImg = new BitmapImage();
        BmpImg.BeginInit();
        BmpImg.StreamSource = new MemoryStream(ms.ToArray());
        BmpImg.EndInit();
    }

    private void Btn_Click(object sender, RoutedEventArgs e)
    {     
        Dispatcher.Invoke(new Action(() => { Image.Source = BmpImg; }));
    }

How to convert a System.Drawing.Image to BitmapImage and display the same on wpf?

Was it helpful?

Solution

BmpImg is created on background thread. You cannot bind to Image Source DP object which is created on thread other than UI thread.

Since you are using Dispatcher, i assume you now how to delegate stuff on UI thread.

So all you need to do is put the creation of BmpImg on UI thread as well via Dispatcher.

You can get UI dispatcher like this as well - App.Current.Dispatcher.

OR

As @Clemens suggested in comments, if you call Freeze() on BitmapImage instance, you can access it across threads.

BmpImg.Freeze()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top