WPF(1)---图片的获取与存储

1---图片通过CGI获取保存到本地 snapshot.cgi快照的意思。

   (1)cgi保存

 public string Address = "http://192.168.58.4/snapshot.cgi/user=admin&pwd=";
        public void PaiZhao()
        {
            FileStream fs = new FileStream("D:\\Image.jpg",FileMode.Create,FileAccess.ReadWrite);
            HttpWebRequest MyHttpWebRequest = null;
            HttpWebResponse MyHttpWebResponse = null;
            Stream MyStream = null;
            try
            {
                MyHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(Address);
                MyHttpWebResponse = (HttpWebResponse)MyHttpWebRequest.GetResponse();
                MyStream = MyHttpWebResponse.GetResponseStream();
            }
            catch(Exception)
            {
            }
            int read = 0;
            byte[] Mybyte=new byte[1024];
            do
            {
                read = MyStream.Read(Mybyte,0,1024);
                fs.Write(Mybyte,0,read);
            }while(read>0);
            MyStream.Flush();
            MyStream.Close();
            MyHttpWebResponse.Close();
            fs.Flush();
            fs.Close();
        }

   (2)stream保存

            FileStream fs = new FileStream(this.txtLuJing.Text.ToString()+"\\"+txtName.Text.ToString()+".jpg", FileMode.Create, FileAccess.ReadWrite);
            Stream MyStream = new MemoryStream((byte[])MyDataSet.Tables[0].Rows[0][2]); //数据库中取出的byte[]数组
            int read = 0;
            byte[] Mybyte = new byte[1024];
            do
            {
                read = MyStream.Read(Mybyte,0,1024);
                fs.Write(Mybyte,0,read);
            } while (read > 0);
            MyStream.Flush();
            MyStream.Close();
            fs.Flush();
            fs.Close();
            System.Windows.MessageBox.Show("保存成功!");

2---对本地图片文件的读取,转换为byte[]数组------》存进数据库

    (1)通过image.save();方式有一定的局限性。

 System.Drawing.Image MyImage = System.Drawing.Image.FromFile("D:\\Image.jpg");
                MemoryStream MyMemoryStream = new MemoryStream();
                MyImage.Save(MyMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg); 
                MyMemoryStream.ToArray();//转为二进制数组 保存到数据库

   (2)通过filestream 内置 file.openRead();方式可直接读取为byte[]数组。

                FileStream fs = File.OpenRead("D:\\Image.jpg");
                byte[] Mybyte = new byte[fs.Length];
                fs.Read(Mybyte, 0, Mybyte.Length);
                fs.Close(); 

3--图片显示到image控件之中

   (1)很据文件路径显示

        private void BtnRead_Click(object sender, RoutedEventArgs e)
        {
            if (MyOpenFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                MyUrl = MyOpenFileDialog.FileName.ToString();                    //获取文件的路径信息
                MyImageName = System.IO.Path.GetFileNameWithoutExtension(MyUrl);//获取图片的名称不包含扩展名
                BitmapImage MyBitmapImage = new BitmapImage(new Uri(MyUrl));   //BitmapImage可通过image.source显示到image控件中
                img1.Source = MyBitmapImage;
            }
        }

   (2)通过MemoryStream内存流显示(byte[]转化为MemoryStream)

 MemoryStream MyMemoryStream = new MemoryStream((byte[])MyDataSet.Tables[0].Rows[0][2]);//将byte[]数组转化为内存流
 System.Drawing.Image MyImage = System.Drawing.Image.FromStream(MyMemoryStream);        //将内存流转化为image类型
 System.Drawing.Bitmap MyBitmap = new System.Drawing.Bitmap(MyImage);                   //将image类型转化为bitmap类型
 IntPtr MyIntPtr = MyBitmap.GetHbitmap();
 System.Windows.Media.ImageSource WPFSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(MyIntPtr, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
 img1.Source = WPFSource;

  (3)图片保存时直接转换为Stream,stream在image中显示

System.Drawing.Image MyImage = System.Drawing.Image.FromStream(MyStream);
System.Drawing.Bitmap MyBitmap = new System.Drawing.Bitmap(MyImage);
IntPtr MyIntPtr = MyBitmap.GetHbitmap();
System.Windows.Media.ImageSource WPFSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(MyIntPtr, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
img1.Source = WPFSource;
//MemoryStream MyMemoryStream = new MemoryStream();
//MyImage.Save(MyMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);  转化为内存流 可以用2显示

  (4)CGI直接获取MemoryStream(显示在image中)

 HttpWebRequest MyHttpWebRequestTest = (HttpWebRequest)WebRequest.Create("http://192.168.58.4/snapshot.cgi/user=admin&pwd=");
            WebResponse MyWebResponse = MyHttpWebRequestTest.GetResponse();
            Stream stream = MyWebResponse.GetResponseStream();
            int read = 0;
            int total = 0;
            byte[] buffer = new byte[1024 * 1024];
            do
            {
                read = stream.Read(buffer, total, 1024);
                total += read;
            } while (read > 0);
            MemoryStream ms = new MemoryStream(buffer, 0, total);
            System.Drawing.Image MyImage3 = System.Drawing.Image.FromStream(ms);
            System.Drawing.Bitmap MyBitmap3 = new System.Drawing.Bitmap(MyImage3);
            IntPtr MyIntPtr3 = MyBitmap3.GetHbitmap();
            System.Windows.Media.ImageSource WPFSource3 = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(MyIntPtr3, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
            img3.Source = WPFSource3;

完整代码:(1)显示图片           

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 System.IO;
using System.Net;
using System.Windows.Threading;
namespace Test_IP_camear
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        public string Address = "http://192.168.58.4/snapshot.cgi/user=admin&pwd=";
        private void btnOpen_Click(object sender, RoutedEventArgs e)
        {
            HttpWebRequest MyHttpWebRequest = null;
            HttpWebResponse MyHttpWebResponse = null;
            MyHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(Address);
            MyHttpWebResponse = (HttpWebResponse)MyHttpWebRequest.GetResponse();
            Stream MyStream = MyHttpWebResponse.GetResponseStream();
            //<1>从(Stream)流文件中读取图片
            System.Drawing.Image MyImage = System.Drawing.Image.FromStream(MyStream);
            System.Drawing.Bitmap MyBitmap = new System.Drawing.Bitmap(MyImage);
            IntPtr MyIntPtr = MyBitmap.GetHbitmap();
            System.Windows.Media.ImageSource WPFSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(MyIntPtr, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
            img1.Source = WPFSource;
            //<2>从(MemoryStream)流文件中读取图片
            MemoryStream MyMemoryStream = new MemoryStream();
            MyImage.Save(MyMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            // byte[] Mybyte = MyMemoryStream.ToArray();可以存储到数据库中
            System.Drawing.Image MyImage2 = System.Drawing.Image.FromStream(MyMemoryStream);
            System.Drawing.Bitmap MyBitmap2 = new System.Drawing.Bitmap(MyImage);
            IntPtr MyIntPtr2 = MyBitmap.GetHbitmap();
            System.Windows.Media.ImageSource WPFSource2 = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(MyIntPtr2, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
            img2.Source = WPFSource2;
            //<3>从(MemoryStream)流文件中读取图片
            HttpWebRequest MyHttpWebRequestTest = (HttpWebRequest)WebRequest.Create("http://192.168.58.4/snapshot.cgi/user=admin&pwd=");
            WebResponse MyWebResponse = MyHttpWebRequestTest.GetResponse();
            Stream stream = MyWebResponse.GetResponseStream();
            int read = 0;
            int total = 0;
            byte[] buffer = new byte[1024 * 1024];
            do
            {
                read = stream.Read(buffer, total, 1024);
                total += read;
            } while (read > 0);
            MemoryStream ms = new MemoryStream(buffer, 0, total);
            System.Drawing.Image MyImage3 = System.Drawing.Image.FromStream(ms);
            System.Drawing.Bitmap MyBitmap3 = new System.Drawing.Bitmap(MyImage3);
            IntPtr MyIntPtr3 = MyBitmap3.GetHbitmap();
            System.Windows.Media.ImageSource WPFSource3 = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(MyIntPtr3, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
            img3.Source = WPFSource3;
        }
    }
}
View Code

               (2)图片通过CGI访问,并保存到本地。

 "listView" HorizontalAlignment="Left" Height="285" Margin="10,10,0,0" VerticalAlignment="Top" Width="250" SelectionChanged="listView_SelectionChanged"/>
        "img1" HorizontalAlignment="Left" Height="129" Margin="282,59,0,0" VerticalAlignment="Top" Width="262"/>
        
xaml
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 System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows.Threading;
using System.Drawing;
using System.Windows.Forms;
namespace TestGuosai
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        SqlConnection conn;
        SqlCommand comm;
        SqlDataAdapter MySqlDataAdapter;
        DataSet MyDataSet;
        public void Getconn()
        {
            conn = new SqlConnection("Data Source=NEWLAND-PC;Initial Catalog=MyImage;Persist Security Info=True;User ID=sa;pwd=123456;");
            conn.Open();
        }
        public void Update()
        {
            Getconn();
            string selsect = "select * from MyImage";
            MySqlDataAdapter = new SqlDataAdapter(selsect,conn);
            MyDataSet = new DataSet();
            MySqlDataAdapter.Fill(MyDataSet);
            listView.Items.Clear();
            for (int i = 0; i < MyDataSet.Tables[0].Rows.Count;i++ )
            {
                listView.Items.Add(MyDataSet.Tables[0].Rows[i][1]);
            }
            this.listView.ScrollIntoView(this.listView.Items[listView.Items.Count-1]);
        }
        private void Window_Loaded_1(object sender, RoutedEventArgs e)
        {
            Update();
        }
        public void PaiZhao()
        {
            string address = "http://192.168.5.4/snapshot.cgi/user=admin&pwd=";
            FileStream fs = new FileStream("D:\\1.jpg",FileMode.Create,FileAccess.ReadWrite);
            HttpWebRequest MyHttpWebRequest=null;
            HttpWebResponse MyHttpWebResponse=null;
            Stream MyStream=null;
            try
            {
                MyHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(address);
                MyHttpWebResponse = (HttpWebResponse)MyHttpWebRequest.GetResponse();
                MyStream = MyHttpWebResponse.GetResponseStream();
            }
            catch(Exception)
            {
            }
            int read = 0;
            byte[] Mybyte=new byte[1024];
            do
            {
                read = MyStream.Read(Mybyte,0,1024);
                fs.Write(Mybyte,0,read);

            }while(read>0);      
            MyStream.Flush();
            MyStream.Close();
            MyHttpWebResponse.Close();
            fs.Flush();
            fs.Close();
        }
        DispatcherTimer tm = new DispatcherTimer();
        int i = 0;
        private void tm_Tick(object sender,EventArgs e)
        {
            i++;
            if (i > Convert.ToInt32(this.txtSpan.Text.ToString()))
            {
                PaiZhao();
                Getconn();
                string address = "D:\\1.jpg";
                System.Drawing.Image MyImage= System.Drawing.Image.FromFile(address);
                System.Drawing.Imaging.ImageFormat MyImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
                MemoryStream MyMemoryStream = new MemoryStream();
                MyImage.Save(MyMemoryStream,MyImageFormat);
                string select = "insert MyImage(MyImageName,MyImageByte) values(@MyImageName,@MyImageByte) ";
                comm = new SqlCommand(select,conn);
                comm.Parameters.Add(new SqlParameter("@MyImageName",SqlDbType.VarChar));
                comm.Parameters.Add(new SqlParameter("@MyImageByte",SqlDbType.Image));
                comm.Parameters[0].Value = DateTime.Now.ToString();
                comm.Parameters[1].Value = MyMemoryStream.ToArray();
                if (comm.ExecuteNonQuery() > 0)
                {
                    System.Windows.MessageBox.Show("保存成功");
                    Update();
                    MyImage.Dispose();
                }
                i = 0;
            }
        }
        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            if (this.txtSpan.Text.ToString() == string.Empty)
            {
                System.Windows.MessageBox.Show("请输入时间间隔!");
                return;
            }
          tm.Tick+=tm_Tick;
          tm.Interval = TimeSpan.FromSeconds(1);
          tm.Start();
        }
        private void listView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Getconn();
            string MyImageName = this.listView.SelectedItem.ToString();
            string select = "select * from MyImage where MyImageName='"+MyImageName+"'";
            MySqlDataAdapter = new SqlDataAdapter(select,conn);
            MyDataSet = new DataSet();
            MySqlDataAdapter.Fill(MyDataSet);
            MemoryStream MyMemoryStream = new MemoryStream((byte[])MyDataSet.Tables[0].Rows[0][2]);
            System.Drawing.Image MyImage = System.Drawing.Image.FromStream(MyMemoryStream);
            System.Drawing.Bitmap MyBitmap = new System.Drawing.Bitmap(MyImage);
            IntPtr MyIntPtr = MyBitmap.GetHbitmap();
            System.Windows.Media.ImageSource WPFImageSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(MyIntPtr,IntPtr.Zero,Int32Rect.Empty,BitmapSizeOptions.FromEmptyOptions());
            img1.Source = WPFImageSource;
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            if (listView.SelectedItem == null)
            {
                System.Windows.MessageBox.Show("请选择图片");
                return;
            }
            Getconn();
            string MyImageName = this.listView.SelectedItem.ToString();
            string select = "select * from MyImage where MyImageName='" + MyImageName + "'";
            MySqlDataAdapter = new SqlDataAdapter(select, conn);
            MyDataSet = new DataSet();
            MySqlDataAdapter.Fill(MyDataSet);
            if (txtName.Text.ToString() == string.Empty)
            {
                System.Windows.MessageBox.Show("请输入图片名!");
            }
            FileStream fs = new FileStream(this.txtLuJing.Text.ToString()+"\\"+txtName.Text.ToString()+".jpg", FileMode.Create, FileAccess.ReadWrite);
            Stream MyStream = new MemoryStream((byte[])MyDataSet.Tables[0].Rows[0][2]);
            int read = 0;
            byte[] Mybyte = new byte[1024];
            do
            {
                read = MyStream.Read(Mybyte,0,1024);
                fs.Write(Mybyte,0,read);
            } while (read > 0);
            MyStream.Flush();
            MyStream.Close();
            fs.Flush();
            fs.Close();
            System.Windows.MessageBox.Show("保存成功!");
        }
        FolderBrowserDialog Open = new FolderBrowserDialog();
        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            if (Open.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.txtLuJing.Text = Open.SelectedPath.ToString();
            }
        }
    }
}
View Code

 

转载于:https://www.cnblogs.com/Probably/p/4605151.html

你可能感兴趣的:(WPF(1)---图片的获取与存储)