使用opencvsharp通过mvvm在image中显示图片

在wpf mvvm框架中,通过Image控件的 Source属性绑定BitmapImage动态显示图片

1.MainWindowVIewModel.cs

using System.Windows.Media.Imaging; //使用BitMapImage类型
using System.Drawing;

//Mat转Bitmap

1         public Bitmap MatToBitmap(Mat image)
2         {
3             return OpenCvSharp.Extensions.BitmapConverter.ToBitmap(image);
4         }
//Mat转BitmapImage
1
public BitmapImage MatToBitmapImage(Mat image) 2 { 3 Bitmap bitmap = MatToBitmap(image); 4 using (MemoryStream stream = new MemoryStream()) 5 { 6 bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png); 7 8 stream.Position = 0; 9 BitmapImage result = new BitmapImage(); 10 result.BeginInit(); 11 // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed." 12 // Force the bitmap to load right now so we can dispose the stream. 13 result.CacheOption = BitmapCacheOption.OnLoad; 14 result.StreamSource = stream; 15 result.EndInit(); 16 result.Freeze(); 17 return result; 18 } 19 }

 

//定义数据属性

 1         private BitmapImage img;
 2 
 3         public BitmapImage Img
 4         {
 5             get { return img; }
 6             set
 7             {
 8                 img = value;
 9                 this.RaisePropertyChanged("Img");
10             }
11         }
1                 Mat image=new Mat(FileNames[i],ImreadModes.Unchanged); //通过路径读入Mat类型的image
3 this.Img = MatToBitmapImage(image); //将image转换为BitmapImage传给Img,Img与Source绑定。

 

//2.MainWindow.xaml

1         <Image HorizontalAlignment="Left" Grid.Row="1" Grid.Column="0" Margin="20,20,0,0" Width="800" Source="{Binding Img}" Grid.RowSpan="2" Height="800" VerticalAlignment="Top"/>
posted @ 2020-01-10 16:17  荼离伤花  阅读(1134)  评论(0编辑  收藏  举报