c# SQL数据库image图片文件的保存于读取
SqlConnection con = new SqlConnection("Persist Security Info=False;User id=sa;pwd=123;database=WDERPDATA_001;server=(local)");
con.Open();
SqlDataAdapter dat = new SqlDataAdapter("select*from TLFGL_LFRY", con);
DataSet set = new DataSet();
dat.Fill(set);
DataTable tb = set.Tables[0];
DataRow rw = tb.Rows[0];
DataColumn cl = tb.Columns[0];
//MessageBox.Show( cl.ColumnName.ToString());
byte[] MyData = new byte[0];
// MyData=tb.Rows[1]["AU_LFRY_ZJZ"];
System.Text.StringBuilder temp = new System.Text.StringBuilder(255);
Image _Image = Image.FromStream(new MemoryStream((byte[])tb.Rows[0]["AU_LFRY_ZJZ"]) );
pictureBox1.Image = _Image;
Bitmap bmmpp = new Bitmap(pictureBox1.Image);
MemoryStream MS = new MemoryStream();
//Bitmap bmp = new Bitmap(VisitorCheckIn.Class1.bmpname);
bmmpp.Save(MS, ImageFormat.Bmp);
Byte[] ImageData = new Byte[MS.Length];
MS.Position = 0;
MS.Read(ImageData, 0, Convert.ToInt32(MS.Length));
string sql00 = "UPDATE TLFGL_LFRY SET AU_LFRY_ZJZ=@Photo WHERE AU_LFRY_ZJH='19850725'";
SqlCommand dbCmd = new SqlCommand(sql00, con);
dbCmd.CommandType = CommandType.Text;
SqlParameter parameter = new SqlParameter("@Photo", SqlDbType.Image, int.MaxValue);
parameter.Value = ImageData;
dbCmd.Parameters.Add(parameter);
dbCmd.ExecuteNonQuery();
将文件转换成二进制方法:
/// <summary>
/// 将文件转换成二进制
/// </summary>
/// <param name="Path">文件路径</param>
/// <returns></returns>
public static byte[] ConvertToBinary(string Path)
{
FileStream stream = new FileInfo(Path).OpenRead();
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, Convert.ToInt32(stream.Length));
return buffer;
}
将二进制转换成文件方法:
using System.IO;
string filePath = "D://a.jpg"; //文件路径
byte[] br = ConvertToBinary(filePath);
FileStream fstream = File.Create(filePath, br.Length);
try
{
fstream.Write(br, 0, br.Length); //二进制转换成文件
}
catch(Exception ex)
{
//抛出异常信息
}
finally
{
fstream.Close();
}
附加:二进制与图片互转
Image aa = new Bitmap(@"E:/photo/tm.jpg");
System.IO.MemoryStream stream = new System.IO.MemoryStream();
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter
= new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(stream, aa); //将图像序列化成二进制流
stream.Position = 0;
Image bb = (Image)formatter.Deserialize(stream); //将二进制流序列成Image