日期:2014-05-19  浏览次数:20868 次

图片如何出入数据库(sql server)
如何将图片保存到数据库里然后再取出并将其显示出来?

------解决方案--------------------
最好是存放地址,在服务器上。读的时候直接取地址不就OK了吗?
------解决方案--------------------
把图片转成文件流。存入数据库就成。
------解决方案--------------------
个人感觉还是存在址的好
一来直接保存图片太大
二来操作也不方便
------解决方案--------------------
private void button1_Click(object sender, EventArgs e)
{
if (this.openFileDialog1.ShowDialog() != DialogResult.OK)
return;
string filename = this.openFileDialog1.FileName;
ImageFormat iformat = null;
switch(filename.Substring(filename.IndexOf( '. ')+1).ToLower())
{
case "bmp ":
iformat=ImageFormat.Bmp;
break;
case "gif ":
iformat=ImageFormat.Gif;
break;
case "jpg ":
iformat=ImageFormat.Jpeg;
break;
}
MemoryStream ms = new MemoryStream();
Image imgae=Image.FromFile(filename);
imgae.Save(ms, iformat);
try
{
conn.Open();
SqlCommand cmd = new SqlCommand( "sp_InsertPhoto2 ", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter( "@name ", SqlDbType.VarChar));
cmd.Parameters.Add(new SqlParameter( "@image ", SqlDbType.Image));
cmd.Parameters[0].Value = Path.GetFileNameWithoutExtension(filename);
cmd.Parameters[1].Value = ms.ToArray();
cmd.ExecuteNonQuery();

}
finally
{
conn.Close();
}
}
private Image StreamToImage(byte[] b)
{
MemoryStream ms = new MemoryStream(b);
return Image.FromStream(ms);
}

private void button2_Click(object sender, EventArgs e)
{
DataSet ds = GetPhotosDataSet();
if (CurrentIndex < ds.Tables[0].Rows.Count-1)
this.pictureBox1.Image = StreamToImage((byte[])ds.Tables[0].Rows[++CurrentIndex][1]);
else
{
CurrentIndex = 0;
this.pictureBox1.Image = StreamToImage((byte[])ds.Tables[0].Rows[CurrentIndex][1]);
}
}