WPFMediaKit照相功能

最近写的一个WPF照相功能,往各位吐槽,提供优化

在WPF 设计器中添加如下代码

xmlns:wpfmedia="clr-namespace:WPFMediaKit.DirectShow.Controls;assembly=WPFMediaKit"

添加显示摄像头图像控件

<wpfmedia:VideoCaptureElement DockPanel.Dock="Top" Name="captureElement" Margin="0,33,0,37"/>

在cs代码文档中添加如下代码

在引用程序集中添加WPFMediaKit程序集

引用类名空间,添加如下代码

using WPFMediaKit;
using WPFMediaKit.DirectShow.Controls;

加载摄像头

void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            //加载摄像头
            cmbCameras.ItemsSource = MultimediaUtil.VideoInputNames;
            if (MultimediaUtil.VideoInputNames.Length > 0)
            {
                cmbCameras.SelectedIndex = 0;
            }
            else
            {
                MessageBox.Show("没有可用摄像头!");
                BtnCap.IsEnabled = false;
                BtnOk.IsEnabled = false;
                BtnNew.IsEnabled = false;
            }
        }

拍照

 private void BtnCap_Click(object sender, RoutedEventArgs e)
        {
            //captureElement. 怎么抓取高清的原始图像
            RenderTargetBitmap bmp = new RenderTargetBitmap((int)captureElement.ActualWidth, (int)captureElement.ActualHeight,
                96, 96, PixelFormats.Default);
            bmp.Render(captureElement);
            BitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bmp));
            using (MemoryStream ms = new MemoryStream())
            {
                encoder.Save(ms);
                CaptureData = ms.ToArray();//将拍照的图像转化为二进制数组
            }
        }

确定拍照

 private void BtnOk_Click(object sender, RoutedEventArgs e)
        {
            if (CaptureData != null)
            {
                DialogResult = true;
            }
            else
            {
                MessageBox.Show("未拍照图像");
                return;
            }
        }

重拍

private void BtnNew_Click(object sender, RoutedEventArgs e)
        {
            captureElement.Play();
        }

摄像头切换

private void cmbCameras_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            captureElement.VideoCaptureSource = (string)cmbCameras.SelectedItem;
        }

将二进制转化成png

private BitmapImage ShowImage(byte[] imgbytes)
        {
            MemoryStream stream = new MemoryStream(imgbytes);
            BitmapImage bmpImg = new BitmapImage();
            bmpImg.BeginInit();
            bmpImg.StreamSource = stream;
            bmpImg.EndInit();
            return bmpImg;
        }

 

图片

 

 

posted @ 2014-03-31 10:20  汉城节度使  阅读(1605)  评论(3编辑  收藏  举报