C# 在 WPF 中显示图像的最佳方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1200838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to display image in WPF
提问by Prashant Cholachagudda
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:
XAML:
<Image Name="imgScan" DataContext="{Binding}" Source="{Binding Path=prescanImage,Converter={StaticResource imgConverter}}" />
C# Assignment:
C# 赋值:
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??
这种方法让我付出了很多(性能)的代价,有没有更好的方法来做到这一点?
采纳答案by Ryan Versaw
Since you're already setting the DataContext
in code (not xaml), why not just skip a few steps?
既然您已经设置了DataContext
in 代码(不是 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;
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
?
如果您有权访问GetMeImage()
,您可能需要考虑更改它以更好地适应您的应用程序 - 它真的需要返回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.
另外,您的第一段代码多久执行一次?您可能需要考虑改变它,或者在需要时允许它改变。