日期:2014-05-17 浏览次数:20990 次
using System; using System.Data; using System.Data.SqlClient; using System.IO; // 下面是从数据库取出图片 try { string getPhoto = @"select photo from gch_Customer_Photo where customerID=1234"; DataSet ds = new DataSet(); sqlDataAdapter1 = new SqlDataAdapter(getPhoto, sqlConnection1); sqlDataAdapter1.Fill(ds); DataRow row = ds.Tables[0].Rows[0]; byte[] bPhoto = new byte[0]; bPhoto = (byte[])row["photo"]; //int arraySize = bPhoto.GetUpperBound(0); MemoryStream memstr = new MemoryStream(bPhoto); pictureBox1.Image = Image.FromStream(memstr, true); existPhoto==true } catch(Exception ex) { Console.WriteLine(ex.ToString()); } // 下面是将图片存入数据库 OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "*.bmp;*.jpg;*.gif|*.bmp;*.jpg;*.gif;*.jpeg"; if(ofd.ShowDialog()==DialogResult.OK) { string filePath = ofd.FileName; FileInfo imageFile = new FileInfo(filePath); if(imageFile.Length > 204800) { Console.WriteLine("图片大小最好不要过大!"); } pictureBox1.Image = Image.FromFile(filePath); if(existPhoto==true) { //如果之前已有图片,可以考虑删除了旧的先 string deleteOld = @"delete from gch_Customer_Photo where customerID=1234"; SqlCommand sqlcmmd = new SqlCommand(deleteOld,sqlConnection1); sqlcmmd.ExecuteNonQuery(); } string getAllPhotos = @"select customerID, photo from gch_Customer_Photo"; DataSet ds = new DataSet(); sqlDataAdapter1 = new SqlDataAdapter(getAllPhotos,sqlConnection1); sqlDataAdapter1.MissingSchemaAction = MissingSchemaAction.AddWithKey; FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read); byte[] bPhoto= new byte[fs.Length]; fs.Read(bPhoto, 0, System.Convert.ToInt32(fs.Length)); fs.Close(); sqlDataAdapter1.Fill(ds); DataRow oneRow = ds.Tables[0].NewRow(); oneRow["customerID"] = 1234; oneRow["photo"] = bPhoto; ds.Tables[0].Rows.Add(oneRow); sqlDataAdapter1.Update(ds); Console.WriteLine("图片入库成功!"); }
------解决方案--------------------
1. 数据库存放的是 Image 类型
2. 用 byte[] data = File.ReadAllBytes(图片路径)
3. byte[] -> MemoryStream -> Bitmap.FromStream
------解决方案--------------------
我一般都说把图片存在本地的文件夹内,然后在数据库里存路径
------解决方案--------------------