一、数据库存储图片类型有以下几种方式:
1、将图片装换为二进制数值(byte[])
byte [] fileData=this.FileUpload1.FileBytes;
2、根据路径将文件装换为二进制数组
private byte[] returnbyte(string strpath)
{
//以二进制方式读文件
FileStream fsMyfile = new FileStream(strpath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
//创建一个二进制数据流读入器,和打开的文件关联
BinaryReader brMyfile = new BinaryReader(fsMyfile);
//把文件指针重新定位到文件的开始
brMyfile.BaseStream.Seek(0, SeekOrigin.Begin);
byte[] bytes = brMyfile.ReadBytes(Convert.ToInt32(fsMyfile.Length.ToString()));
//关闭以上的new的各个对象
brMyfile.Close();
return bytes;
}
3、Image类型得到二进制数组
public static byte[] Getbyte(Image img)
{
MemoryStream stream = new MemoryStream();
img.Save(stream, ImageFormat.Jpeg); //Image.FromFile(Path).Save(stream, ImageFormat.Jpeg); ;
byte[] mydata = new byte[stream.Length];
mydata = stream.ToArray();
stream.Close();
return mydata;
}
二、图片的显示
读取p_w_picpath类型的数据并显示在网页上的方式如下
1、直接返回p_w_picpath类型
private System.Drawing.Image GetImageDataFromDB()
{
string sql = "select Picture from TPicture where ID=1";
string strconn = System.Configuration.ConfigurationManager.ConnectionStrings["Conn"].ToString();
SqlConnection conn = new SqlConnection(strconn);
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
byte[] filedata = (byte[])cmd.ExecuteScalar();
conn.Close();
System.IO.MemoryStream ms = new MemoryStream(filedata);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
return img;
}
2、利用页面输出来显示图片
页面ShowImage.aspx(Page_Load)方法
protected void Page_Load(object sender, EventArgs e)
{
string sql = "select Picture from TPicture";
string strconn = System.Configuration.ConfigurationManager.ConnectionStrings["Conn"].ToString();
SqlConnection conn = new SqlConnection(strconn);
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataTable dt = new DataTable();
da.Fill(dt);
byte[] logoimg = (byte[])dt.Rows[0]["Picture"];
if (logoimg.Length > 0)
{
System.Drawing.Image img;
MemoryStream ms = new MemoryStream(logoimg);
Response.Clear();
Response.ContentType = "p_w_picpath/gif";
Response.OutputStream.Write(logoimg, 0, logoimg.Length);
Response.End();
}
}
图片路径写为:<img src="ShowImage.aspx" />
图片在数据库中的类型设置为p_w_picpath类型
示例:
SqlConnection conn = new SqlConnection(strconn);
conn.Open();
string sql = "insert into TPicture(Picture) values(@Picture)";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter para = new SqlParameter("@Picture", SqlDbType.Image);
//para.Value = FileUpload1.FileBytes;
para.Value = Getbyte(null);//字节数组
cmd.Parameters.Add(para);
cmd.ExecuteNonQuery();