Prashant Cholachagudda
Prashant Cholachagudda

Reputation: 13092

Best way to display image in WPF

Currently I'm working on a Ultrasound scanning project, which displays the continues images aquired from a probe, to do that I'm writing following code.

XAML:

<Image Name="imgScan" DataContext="{Binding}" Source="{Binding Path=prescanImage,Converter={StaticResource imgConverter}}" />

C# Assignment:

Bitmap myImage = GetMeImage();
imageMem = new MemoryStream();
myImage .Save(imageMem, ImageFormat.Png);
imgScan.DataContext = new { prescanImage = imageMem.ToArray() };

Converter:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    if (value != null && value is byte[])
    {
      byte[] ByteArray = value as byte[];
      BitmapImage bmp = new BitmapImage();
      bmp.BeginInit();
      bmp.StreamSource = new MemoryStream(ByteArray);
      bmp.EndInit();
      return bmp;
    }
    return null;
}

This method is costing me lot of (performance), is there any better way to do it??

Upvotes: 4

Views: 13535

Answers (1)

Ryan Versaw
Ryan Versaw

Reputation: 6495

Since you're already setting the DataContext in code (not xaml), why not just skip a few steps?

Bitmap myImage = GetMeImage();
imageMem = new MemoryStream();
myImage.Save(imageMem, ImageFormat.Png);
BitmapImage bmp = new BitmapImage();
bmp.BeginInit();
bmp.StreamSource = new MemoryStream(imageMem.ToArray());
bmp.EndInit();
imgScan.Source = bmp;

If you have access to GetMeImage(), you may want to consider altering it to better fit into your application - Does it really need to return a Bitmap?

Also, how often is your first piece of code being executed? You may want to consider altering that, or allowing it to vary when it needs to.

Upvotes: 3

Related Questions