bred_one
bred_one

Reputation: 147

WPF Image source not loaded from stream

I've got WCF service to catch webcam images and send to client, it works great in my WinForms app. I decided to crate WPF client app.

I've got code:

void timer1_Tick(object sender, EventArgs e)
{
       counter++;
       try
       {
            Stream imageStream = client.GetImage();
            using (MemoryStream stream = new MemoryStream())
            {
                imageStream.CopyTo(stream);
                int size = (int)stream.Length;
                cam_img.Source = BitmapFrame.Create(stream,
                                                  BitmapCreateOptions.None,
                                                  BitmapCacheOption.OnLoad);
            }
            System.Diagnostics.Debug.WriteLine(counter);
       }
       catch (System.ServiceModel.CommunicationException ex)
       {
            if (ex.InnerException is System.ServiceModel.QuotaExceededException)
            {

            }
            else
            { 
                throw ex;
            }

       }
       catch (System.Exception ex)
       {

       }
}

cam_img is a Image Control. In debugger mode i see that stream contains data, but cam_img.source is null in every tick event.

Next question is, do i have to implement propertychanged event to make dynamic binding with image? Or assign to cam_img.source in each timer tick is enough to see dynamic changing on control?

Upvotes: 0

Views: 470

Answers (1)

terry
terry

Reputation: 1589

Question 2:

No, you don't need the PropertyChanged, you can just assign the cam_img.Source property in each timer tick. Please make sure you're setting the cam_img.Source in the UI thread, otherwise you'll get an InvalidOperationException says something like:

The calling thread cannot access this object because a different thread owns it.

Question 1:

If your imageStream contains the data, and you prefer the MemoryStream, then you should call stream.Seek(0, SeekOrigin.Begin); to move the position back before you call the BitmapFrame.Create.

Your current code will cause an exception when creating the BitmapFrame, and the exception is caught, so that's why the cam_img.Source is never set, and was still the default 'null' value.

Upvotes: 1

Related Questions