最近试验需求,用到了sql server中的image字段,存取方法如下:
存
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public void Save() { using (System.IO.FileStream stream = new System.IO.FileStream()) { byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, (int)stream.Length); stream.Close(); string strName = System.IO.Path.GetFileNameWithoutExtension(file); SqlCommand cmd = new SqlCommand("Insert into Temp(name,photo) values(@name,@image)", sqlConn); cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = strName; cmd.Parameters.Add("@image", SqlDbType.Image).Value = buffer; cmd.ExecuteNonQuery(); } }
|
取:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public void GetImage() { SqlCommand cmd = new SqlCommand(@"SELECT name, photo FROM Temp", sqlConn); sqlConn.Open(); SqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { image_filename = (string)reader.GetValue(0); byte[] image_bytes = (byte[])reader.GetValue(1); MemoryStream ms = new MemoryStream(image_bytes); Bitmap bmap = new Bitmap(ms); return bmap;
} }
|