SQLserver C#將圖片以二進位制方式儲存到資料庫,再從資料庫讀出圖片
阿新 • • 發佈:2018-12-12
一 儲存到資料庫
1、建立資料表UserPhoto
userID為varchar(50) 設定為標識列unique不能重複 alter table UserPhoto add unique(UserID)
photo為image
2、寫一個類,主要有三個方法
(1)連線資料庫的類ConnectionOpen()
(2)判斷圖片型別轉換byte[]陣列ImageToBytes(Image image)
(3)操作資料庫將轉換的二進位制寫進資料庫
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace importImage { class Class1 { private SqlConnection ConnectionOpen() { string connectionString = "Server = 192.168.31.214; Database =Attendance; User ID = sa ; Password = dengrui2018;"; SqlConnection conn = new SqlConnection(connectionString); conn.Open(); return conn; } public static byte[] ImageToBytes(Image image) { if (image == null) { return null; } ImageFormat format = image.RawFormat; using (MemoryStream ms = new MemoryStream()) { if (format.Equals(ImageFormat.Jpeg)) { image.Save(ms, ImageFormat.Jpeg); } else if (format.Equals(ImageFormat.Png)) { image.Save(ms, ImageFormat.Png); } else if (format.Equals(ImageFormat.Bmp)) { image.Save(ms, ImageFormat.Bmp); } else if (format.Equals(ImageFormat.Gif)) { image.Save(ms, ImageFormat.Gif); } else if (format.Equals(ImageFormat.Icon)) { image.Save(ms, ImageFormat.Icon); } byte[] buffer = new byte[ms.Length]; //Image.Save()會改變MemoryStream的Position,需要重新Seek到Begin ms.Seek(0, SeekOrigin.Begin); ms.Read(buffer, 0, buffer.Length); return buffer; } } public bool InsertPerImage(string rowAutoID, Image perImage) { SqlConnection conn = ConnectionOpen(); int i = 0; if (perImage == null) { SqlCommand com = new SqlCommand("insert into UserPhoto(UserID) values('100020')", conn); com.Parameters.Add("UserID", SqlDbType.VarChar);//資料庫裡userID是varchar,這裡轉換為varchar com.Parameters["UserID"].Value = rowAutoID; i = com.ExecuteNonQuery(); } else { SqlCommand com = new SqlCommand("insert into UserPhoto(UserID,photo) values(@UserID,@photo)", conn); com.Parameters.Add("UserID", SqlDbType.VarChar); com.Parameters["UserID"].Value = rowAutoID; com.Parameters.Add("photo", SqlDbType.Image); com.Parameters["photo"].Value = ImageToBytes(perImage);//呼叫方法將圖片轉換為二進位制 i = com.ExecuteNonQuery();//返回受影響的函式 } if (i > 0) { conn.Close(); return true; } else { conn.Close(); return false; } } } }
3、呼叫方法
private void button5_Click(object sender, EventArgs e) { Class1 c1 = new Class1(); string id = "10002"; //呼叫方法 傳遞兩個引數 編號,圖片的路徑 bool aa = c1.InsertPerImage(id, Image.FromFile(@"E:\ssdVS\專案\importImage\importImage\image\bananer.jpg")); MessageBox.Show(aa.ToString()); //如果返回為true 則新增成功 }
二 從資料庫獲取二進位制轉換為圖片
有空完善.....