private void Form1_Load(object sender, EventArgs e) { #region 保存数据库 string url = @"C:\Users\Administrator\Desktop\tiger.jpg"; byte[] dd = GetPictureData(url); kkkkk(dd);//保存到数据库中 #endregion Read();// 从数据库中读取保存到 C盘 } /// <summary> /// 保存到数据库 /// </summary> /// <param name="imgBytesIn"></param> private void kkkkk(byte[] imgBytesIn) { try { SqlConnection con = new SqlConnection("server=192.168.1.118,1433;uid=sa;pwd=123456;database=aa"); con.Open(); SqlCommand cmd = new SqlCommand("insert into aaaa (img) values( @Image ) ;", con); cmd.Parameters.Add("@Image", SqlDbType.Image); cmd.Parameters["@Image"].Value = imgBytesIn; cmd.ExecuteNonQuery(); con.Close(); MessageBox.Show("图片上传成功"); } catch { MessageBox.Show("您选择的图片不能被读取或文件类型不对!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } /// <summary> /// 从数据库中 图片 并且保存到C盘 /// </summary> public void Read() { byte[] MyData = new byte[0]; using (SqlConnection conn = new SqlConnection("server=192.168.1.118,1433;uid=sa;pwd=123456;database=aa")) { conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = "select * from aaaa"; SqlDataReader sdr = cmd.ExecuteReader(); sdr.Read(); object o = sdr["img"]; MyData = (byte[])sdr["img"];//读取第一个图片的位流 int ArraySize= MyData.GetUpperBound(0);//获得数据库中存储的位流数组的维度上限,用作读取流的上限 FileStream fs = new FileStream(@"c:\00.jpg", FileMode.OpenOrCreate, FileAccess.Write); fs.Write(MyData, 0, ArraySize); fs.Close(); //-- 写入到c:\00.jpg。 conn.Close(); Console.WriteLine("读取成功");//查看硬盘上的文件 } } /// <summary> /// 根据路径将图片转换成 byte[] /// </summary> /// <param name="imagepath"></param> /// <returns></returns> public byte[] GetPictureData(string imagepath) { /**/ ////根据图片文件的路径使用文件流打开,并保存为byte[] FileStream fs = new FileStream(imagepath, FileMode.Open);//可以是其他重载方法 byte[] byData = new byte[fs.Length]; fs.Read(byData, 0, byData.Length); fs.Close(); return byData; }
标签:fs,数据库,cmd,保存,SQL,new,byte From: https://www.cnblogs.com/xkdn/p/17698574.html