C# WPF中图片剪裁并显示

XAML:


    
        
            
            
        
        
            
            
        
        
        
        
        
    

wpf代码:

  1. 首先要在nuget上安装emgucv

using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.CV.CvEnum;
using System;
using System.Windows;
using System.Drawing;
using System.Windows.Media;
using System.Windows.Media.Imaging;


namespace WpfApp6
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        [System.Runtime.InteropServices.DllImport("gdi32.dll")]
        public static extern bool DeleteObject(IntPtr hObject);


        public static ImageSource ChangeBitmapToImageSource(Bitmap bitmap)
        {
            IntPtr hBitmap = bitmap.GetHbitmap();
            ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());


            if (!DeleteObject(hBitmap))
            {
                throw new System.ComponentModel.Win32Exception();
            }
            return wpfBitmap;
        }


        private void Window_Loaded(object sender, RoutedEventArgs e)
        {


            Rectangle rectangle = new Rectangle(100, 100, 212, 564);//int x, int y, int width, int height
           
            /***加载image类型图片剪裁显示到wpf image控件 ***/
            Image Img = new Image(new Bitmap(@"C:\Users\admin\source\repos\WpfApp6\WpfApp6\bin\Debug\11.jpg"));//路径声明
            Image Sub1 = Img.GetSubRect(rectangle);
            image2.Source = ChangeBitmapToImageSource(Sub1.ToBitmap());


            /***加载mat类型图片剪裁显示到wpf image控件***/
            Mat SCr = new Mat(@"C:\Users\admin\source\repos\WpfApp6\WpfApp6\bin\Debug\22.jpg", LoadImageType.AnyColor);
            image3.Source = ChangeBitmapToImageSource(SCr.Bitmap);
            Image Sub2 = SCr.ToImage().GetSubRect(rectangle);
            image4.Source = ChangeBitmapToImageSource(Sub2.ToBitmap());
        }
    }
}

运行结果:

C# WPF中图片剪裁并显示_第1张图片

欢迎关注公众号: dotnet编程大全

技术群: 需要进技术群的添加小编微信mm1552923,备注:加群;

你可能感兴趣的:(c#,wpf,开发语言)