PictureBox中的Image对象(或者图片)转存到数据库
主要有两个点:
1.图片Image对象 ”保存“到MemoryStream中;
image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg);
2.二进制数据插入到数据库的操作。
SqlParameter param = new SqlParameter("ImgData", SqlDbType.VarBinary, imageBytes.Length); param.Value = imageBytes; cmd.Parameters.Add(param);
下面贴上代码
private void button1_Click(object sender, EventArgs e) { byte[] imageBytes = GetImageBytes(pictureBox1.Image); string connStr = "SQL Server连接字符串"; using (SqlConnection conn = new SqlConnection(connStr)) { string sql = "Insert Into T_Img Values (@ImgData) "; using (SqlCommand cmd = new SqlCommand(sql)) { SqlParameter param = new SqlParameter("ImgData", SqlDbType.VarBinary, imageBytes.Length); param.Value = imageBytes; cmd.Parameters.Add(param); cmd.Connection = conn; conn.Open(); int i = cmd.ExecuteNonQuery(); MessageBox.Show(i.ToString()); } } } private byte[] GetImageBytes(Image image) { MemoryStream mstream = new MemoryStream(); image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] byteData = new Byte[mstream.Length]; mstream.Position = 0; mstream.Read(byteData, 0, byteData.Length); mstream.Close(); return byteData; }
本博客(liqipeng)除非已明确说明转载,否则皆为liqipeng原创或者整理,转载请保留此链接:https://www.cnblogs.com/liqipeng/archive/2012/06/30/4576223.html。
本博客(liqipeng)除非已明确说明转载,否则皆为liqipeng原创或者整理,转载请保留此链接:https://www.cnblogs.com/liqipeng/archive/2012/06/30/4576223.html。
如果你觉得这篇文章对你有帮助或者使你有所启发,请点击右下角的推荐按钮,谢谢,:)