在WPF中显示图像的最佳方式
-
05-07-2019 - |
题
目前我正在研究超声波扫描项目,该项目显示从探测器获取的连续图像,为此我正在编写以下代码。
XAML:
<Image Name="imgScan" DataContext="{Binding}" Source="{Binding Path=prescanImage,Converter={StaticResource imgConverter}}" />
C#作业:
Bitmap myImage = GetMeImage();
imageMem = new MemoryStream();
myImage .Save(imageMem, ImageFormat.Png);
imgScan.DataContext = new { prescanImage = imageMem.ToArray() };
转换器:
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;
}
这种方法耗费了很多(性能), 有没有更好的方法呢?
解决方案
由于您已经在代码中设置了 DataContext
(而不是xaml),为什么不跳过几步呢?
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;
如果您可以访问 GetMeImage()
,您可能需要考虑更改它以更好地适应您的应用程序 - 它是否真的需要返回 Bitmap
?
此外,您的第一段代码执行的频率是多少?您可能需要考虑更改它,或允许它在需要时改变。
不隶属于 StackOverflow