C#与Kinect v1(2):图片保存与多线程处理

来源:互联网 发布:企业淘宝怎么注册 编辑:程序博客网 时间:2024/05/16 22:18

1. 增加图片保存按钮

首先利用界面编辑器添加按钮,并添加响应函数事件:saveButton_Click

<StackPanel Orientation="Horizontal" >    <Image x:Name="kinectVideo" Height="480" Width="640" />    <StackPanel Width="121" >        <Button x:Name="saveButton" Content="保存图片" Margin="29,20,0,20" Click="saveButton_Click" VerticalAlignment="Center" RenderTransformOrigin="0.538,-0.689" Height="30" HorizontalAlignment="Left" Width="77"/>    </StackPanel></StackPanel>
接着绑定一个状态标志位,表明按钮是否按下了。这里变量名是bool takePicture

事件响应函数如下,会打开一个常见的路径选择框,选择需要保存的位置。

添加Using声明,using System.IO; // 保存图片

private void saveButton_Click(object sender, RoutedEventArgs e){    // Set the flag to trigger a snapshot    takePicture = true;    // Configure save file dialog box    Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();    dlg.FileName = "SnapShot"; // Default file name    dlg.DefaultExt = ".jpg"; // Default file extension    dlg.Filter = "Pictures (.jpg)|*.jpg"; // Filter files by extension    // Process save file dialog box results    if (dlg.ShowDialog() == true)    {      // Save document      string filename = dlg.FileName;      using (FileStream stream = new FileStream(filename, FileMode.Create))      {        JpegBitmapEncoder encoder = new JpegBitmapEncoder();        encoder.Frames.Add(BitmapFrame.Create(pictureBitmap));        encoder.Save(stream);       }     }}

2. 显示界面的图片与保存的图片利用多线程来分离

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;using Microsoft.Kinect;using System.IO; // 保存图片using System.Threading; // 添加线程引用namespace KinectCam{    /// <summary>    /// MainWindow.xaml 的交互逻辑    /// </summary>    public partial class MainWindow : Window    {        // 公共变量        KinectSensor myKinect;        WriteableBitmap WriteableBitmap = null;// 最新接收到的图片数据        int width = 0;        int height = 0;        bool takePicture = false;        BitmapSource pictureBitmap = null; // 将保存的图片数据        Thread updateVideoThread; // 创建线程对象        byte[] colorData = null; // 保存获取的数据        bool displayActive = true; // 控制是否刷新显示        public MainWindow()        {            InitializeComponent();        }        private void Window_Loaded(object sender, RoutedEventArgs e)        {            if (KinectSensor.KinectSensors.Count == 0)            {                MessageBox.Show("No Kinects detected", "Camera Viewer");                Application.Current.Shutdown();            }            try            {                myKinect = KinectSensor.KinectSensors[0];                myKinect.ColorStream.Enable();                myKinect.Start();            }            catch            {                MessageBox.Show("The first Kinect initialize failed", "Camera Viewer");                Application.Current.Shutdown();            }            updateVideoThread = new Thread(new ThreadStart(videoDisplay));// 初始化线程对象            updateVideoThread.Start();// 启动线程        }                        void videoDisplay()// 接收滑动条数值变化,CheckBox等交互信息        {            while (displayActive)// 确保关闭时,后台也同样关闭            {                using (ColorImageFrame colorFrame = myKinect.ColorStream.OpenNextFrame(10))// 处理完主动去获取数据而非被动的事件响应                {                    if (colorFrame == null) continue;                    if (colorData == null)                        colorData = new byte[colorFrame.PixelDataLength];                    width = colorFrame.Width;                    height = colorFrame.Height;                    colorFrame.CopyPixelDataTo(colorData);// 从Kinect获取的数据都在这个地方了!!!!!!!!!!!!!                    if (takePicture)                    {                        pictureBitmap = BitmapSource.Create( colorFrame.Width, colorFrame.Height,                                                            96, 96, PixelFormats.Bgr32, null,                                                            colorData,                                                            colorFrame.Width * colorFrame.BytesPerPixel );                                       takePicture = false;                    }                    Dispatcher.Invoke(new Action(() => updateDisplay()));// 通知系统窗口在背后进行实际的更新动作                }            }                        // when we get here the program is ending – stop the sensor            myKinect.Stop();        }        void updateDisplay() // 在这里才真正更新,将从kinect获取的数据填入到bitmap中        {            if (WriteableBitmap == null)            {                this.WriteableBitmap = new WriteableBitmap(  width,                                                             height,                                                             96,  // DpiX                                                             96,  // DpiY                                                             PixelFormats.Bgr32,                                                             null);                kinectVideo.Source = WriteableBitmap;            }            WriteableBitmap.WritePixels( new Int32Rect(0, 0, width, height),                                         colorData, // 经过滑动滤波后的实际图像数据                                         width * 4, // stride,一行的字节数(跟分辨率有关这里是640)                                         0   // offset into the array - start at 0                                          );        }        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)        {            displayActive = false; // 保证关闭程序后,线程不在后台运行        }        private void saveButton_Click(object sender, RoutedEventArgs e)        {            // Set the flag to trigger a snapshot            takePicture = true;            // Configure save file dialog box            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();            dlg.FileName = "SnapShot"; // Default file name            dlg.DefaultExt = ".jpg"; // Default file extension            dlg.Filter = "Pictures (.jpg)|*.jpg"; // Filter files by extension            // Process save file dialog box results            if (dlg.ShowDialog() == true)            {                // Save document                string filename = dlg.FileName;                using (FileStream stream = new FileStream(filename, FileMode.Create))                {                    JpegBitmapEncoder encoder = new JpegBitmapEncoder();                    //encoder.Frames.Add(BitmapFrame.Create(pictureBitmap));// 不同线程中不允许访问!!!                    encoder.Frames.Add(BitmapFrame.Create(WriteableBitmap));                    encoder.Save(stream);                }            }        }    }}




0 0
原创粉丝点击