已经实现将图片转化为2进制字符串存入数据库的表中。如何取出该图片并显示在winform窗体的picturebox中?
将图片转化为2进制的代码如下:
如何实现从数据库取出?
using System; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.IO; using System.Windows.Forms; namespace MyApp { public partial class Form1 : Form { public Form1() { InitializeComponent(); this.pictureBox1.Image = Image.FromFile(@"D:\Firen.jpg"); } //保存图像到数据库 private void btnSaveImage_Click(object sender, EventArgs e) { string connStr = @"Data Source=.\sqlexpress;Initial Catalog=TestDb;Integrated Security=True"; using (SqlConnection conn = new SqlConnection(connStr)) { using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = "INSERT INTO [dbo].[ImageTable]([ImageId],[ImageBytes]) VALUES (@ImageId,@ImageBytes)"; cmd.CommandType = CommandType.Text; SqlParameter parmImageId = new SqlParameter("@ImageId", SqlDbType.Int); parmImageId.Value = 1; cmd.Parameters.Add(parmImageId); SqlParameter parmImageBytes = new SqlParameter("@ImageBytes", SqlDbType.VarBinary); using (MemoryStream ms = new MemoryStream()) { pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); parmImageBytes.Value = ms.GetBuffer(); } cmd.Parameters.Add(parmImageBytes); conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } } } //加载图像 private void btnLoadImage_Click(object sender, EventArgs e) { string connStr = @"Data Source=.\sqlexpress;Initial Catalog=TestDb;Integrated Security=True"; using (SqlConnection conn = new SqlConnection(connStr)) { using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = "SELECT [ImageBytes] FROM [dbo].[ImageTable] WHERE [ImageId]=@ImageId"; cmd.CommandType = CommandType.Text; SqlParameter parmImageId = new SqlParameter("@ImageId", SqlDbType.Int); parmImageId.Value = 1; cmd.Parameters.Add(parmImageId); conn.Open(); byte[] imageBytes = (byte[])cmd.ExecuteScalar(); using (MemoryStream ms = new MemoryStream(imageBytes)) { pictureBox1.Image = Image.FromStream(ms); } conn.Close(); } } } } }
表结构
非常感谢,参考了你的代码后我感觉自己写的方法有很大的不足,进行了修改。看来我还有很多地方需要好好研究!