又来麻烦各位了,关于保存picturebox中的图片到数据库
之前知道用vb里怎么将picturebox中的图片保存到数据库
.net里怎么做捏,请教了...
备注:图片是设计时添加到控件中的.
谢谢..
------解决方案--------------------使用如下的方法得到Image的Byte[]这个字节数组,然后把这个字节数据存到数据库就可以了:
Image img = this.getImage();
MemoryStream stream = new MemoryStream();
img.Save(stream, ImageFormat.Bmp);
byte[] bts = stream.GetBuffer();
------解决方案--------------------再参考下面的代码:
OpenFileDialog of = new OpenFileDialog();
if (of.ShowDialog(this) == DialogResult.OK)
{
Image img = Image.FromFile(of.FileName);
MemoryStream ms = new MemoryStream();
img.Save(ms, img.RawFormat);
string sql = "insert into Pictures (Name, Photo) Values(@Name, @Photo) ";
SqlConnection cn = new SqlConnection();
cn.ConnectionString = this.txtConnect.Text;
cn.Open();
SqlCommand cm = cn.CreateCommand();
cm.CommandText = sql;
cm.Parameters.Add( "@Name ", SqlDbType.VarChar, 500).Value=of.FileName;
cm.Parameters.Add( "@Photo ", SqlDbType.Image).Value = ms.GetBuffer();
cm.ExecuteNonQuery();
}
------解决方案--------------------MemoryStream ms = new MemoryStream();
this.pictureBox.Image.Save(ms, this.pictureBox.Image.RawFormat);
string sql = "insert into Pictures (Name, Photo) Values(@Name, @Photo) ";
SqlConnection cn = new SqlConnection();
cn.ConnectionString = this.txtConnect.Text;
cn.Open();
SqlCommand cm = cn.CreateCommand();
cm.CommandText = sql;
cm.Parameters.Add( "@Name ", SqlDbType.VarChar, 500).Value=of.FileName;
cm.Parameters.Add( "@Photo ", SqlDbType.Image).Value = ms.GetBuffer();
cm.ExecuteNonQuery();
------解决方案--------------------定义数据库字段类型为image或者二进制,然后把图片转化成byte数组在存储过程中作参数传入保存就ok了!
------解决方案--------------------以字節的形式進行數據庫的存儲和 讀取
//ImageToByte(Image img)
public static byte[] ImageToByte(Image img)
{
byte[] byt = null;
ImageConverter imgCvt = new ImageConverter();
object obj = imgCvt.ConvertTo(img, typeof(byte[]));
byt = (byte[])obj;
return byt;
}
//ByteToImage(byte[] byt)
public static Image ByteToImage(byte[] bytImage)
{
Image img = null;
if (bytImage.Length == 0)
{
return img;
}
else
{
ImageConverter imgCvt = new ImageConverter();
object obj = imgCvt.ConvertFrom(bytImage);
img = (Image)obj;
return img;
}
}