0

The idea is to process a loaded image. I first wanted to process it that way, that there is a white/black line going through the image. Actual the problem is, that a new Thread (for Thread.Sleep) freezes the whole UI, while processing. And when I try a Dispatcher, the image doesn't update.

So I got a ProcessingClass:

public WriteableBitmap GetProcessedPicture(int i)
        {
            WriteableBitmap wb = image.image;

            Process(ref wb, i);

            return wb;
        }

        private void Process(ref WriteableBitmap wb, int j)
        {
            int stride = wb.PixelWidth * (wb.Format.BitsPerPixel + 7) / 8;

            byte[] data = new byte[stride * wb.PixelHeight];

            for (int i = 0; i < data.Length; i++) data[i] = 255;

//just to see some changes
            wb.WritePixels(new Int32Rect(j, 0, 100, 100), data, stride, 0);

        }

And the MainViewModel class (I'm using MVVM light) with:

public void Start_Click()
        {
                        Application.Current.Dispatcher.BeginInvoke(new Action(() =>
        {
            for (int i = 0; i < 100; i++)
            {
                ImageSource = processingClass.GetProcessedPicture(i);

                Thread.Sleep(100);
            }
        }));

            };

Thanks for the help.

1 Answers1

0

I don't think ImageSource (assuming it binds to Image.Source) accepts a WriteableBitmap. You have to convert it to a BitmapImage first!

Adjusting your code a bit I'd do something like:

public void Start_Click()
{
    var t = new Task(() =>
    {
        for (var i = 0; i < 100; i++)
        {
            var writeablebitmap = processingClass.GetProcessedPicture(i);
            var bitmapImage = processingClass.ConvertToBitmapImage(writeablebitmap);

            Application.Current.Dispatcher.BeginInvoke(new Action(() =>
            {
                ImageSource = bitmapImage;
            }));

            Thread.Sleep(100);
        }
    });
    t.Start();
}

This way you're not stalling the UI thread with your image processing, but you still update the image on the UI thread.

As for converting your WriteableBitmap to a BitmapImage, there are plenty of resources available on the internet, like this one

Community
  • 1
  • 1
ManIkWeet
  • 1,298
  • 1
  • 15
  • 36
  • Yes, `ImageSource` is Image.Source, but it accepts `WriteableBitmap` there is no problem when I initialize it. But I tried your code and it throws me the same `InvalidOperationException`, I got eralier. – Matthias Jun 07 '16 at 12:45
  • Did you create the WriteableBitmap on the UI thread? Otherwise that might expain your `InvalidOperationException`. You might also want to read the Remarks at https://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap.aspx to make sure you're doing it right when it comes to threading. – ManIkWeet Jun 08 '16 at 06:59