简体   繁体   中英

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??

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM