我们在用C#和SQL Server数据库开发应用程序时,常常会用到图片处理的问题。那么C#是怎样将图片保存到SQL Server数据库中的呢?本文我们通过一个实例代码来介绍这一过程。
首先打开一个图片文件代码如下:
private void Image(object sender, EventArgs e) { OpenFileDialog fileDialog = new OpenFileDialog(); fileDialog.Filter = "图片文件|*.jpg"; fileDialog.Multiselect = false; if (fileDialog.ShowDialog() == DialogResult.OK) { //图片地址 this.textBoxImage.Text = fileDialog.FileName; } }
保存图片:
private void Save(object sender, EventArgs e) { //把图片转换为二进制保存 Stream stream = new FileStream(this.textBoxImage.Text.Trim(), FileMode.Open); byte[] data=new byte[stream.Length]; stream.Read(data, 0, data.Length); stream.Close(); //保存到数据库 string connectionString = 连接字符串; SqlConnection connection = new SqlConnection(connectionString); //sql语句 string sql="@INSERT INTO 数据库名称 (Image) VALUES(@Image)"; SqlCommand cmd = new SqlCommand(sql, connection); SqlParameter parameter=new SqlParameter () {ParameterName="@Image",Value=data,SqlDbTypeSqlDbType=SqlDbType.Image}; cmd.Parameters.AddRange(parameters); if (connection.State == ConnectionState.Closed) { connection.Open(); } int count = cmd.ExecuteNonQuery(); if (count > 0) { MessageBox.Show("success"); } else { MessageBox.Show("failed"); } connection.Close(); } }
执行完上述代码,就可以成功地将图片保存到SQL Server数据库中了。