public static Stream myStream;//上传图片的流
#region 上传图片按钮事件
/// <summary>
/// 上传图片按钮事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnPicture_Click(object sender, EventArgs e)
{
OpenFileDialog myopen = new OpenFileDialog();
myopen.Filter = "jpg|*.JPG|*.GIF|*.gif|*.BMP|*.bmp";
if (myopen.ShowDialog() == DialogResult.OK)
{
myStream = myopen.OpenFile();
Image image = Image.FromFile(myopen.FileName);
this.pictureBox1.Image = image;
}
}
#endregion
mybasic.Picture = getImage();
#region 根据图片流获得字节数据
/// <summary>
/// 根据图片的路径获得字节数据
/// </summary>
/// <param name="picturePath"></param>
/// <returns></returns>
public byte[] getImage()
{
byte[] imagebytes = null;
if (myStream != null)
{
int length = (int)myStream.Length;
imagebytes = new byte[length];
myStream.Read(imagebytes, 0, length);
}
return imagebytes;
}
#endregion
//存入数据库中时判断是否为空
if (myInfor.Picture == null)
{
strBasic.Append(" NULL)");
}
else
{
strBasic.Append("@image)");
mycom.Parameters.Add("@image", SqlDbType.Image);
mycom.Parameters["@image"].Value = myInfor.Picture;
}
//写入数据库
OpenFileDialog sf = new OpenFileDialog();
sf.Filter = "(*.jpg)|*.jpg";
sf.ShowDialog();
Image img = Image.FromFile(sf.FileName);
this.pictureBox1.Image = img;
SqlConnection conn = new SqlConnection("server=.\\sqlexpress;uid=sa;database=master");
SqlCommand cmd = new SqlCommand("insert into imgs values(@img)", conn);
cmd.Parameters.Add(new SqlParameter("@img", SqlDbType.Image));
MemoryStream ms = new MemoryStream();
img.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
cmd.Parameters[0].Value = ms.ToArray();
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
ms.Close();
//读数据库
SqlConnection conn = new SqlConnection("server=.\\sqlexpress;uid=sa;database=master");
conn.Open();
SqlCommand cmd = new SqlCommand("select img from imgs where id = 1",conn);
byte[]a = (byte[])cmd.ExecuteScalar();
MemoryStream ms = new MemoryStream();
ms.Write(a, 0, a.Length);
this.pictureBox1.Image = new Bitmap(ms);