C# 保存图片与读取图片至 SQL Server 数据库方法
本文详细讲解如何在 C# Windows Forms 应用程序中将图片保存为二进制数据存入 SQL Server 数据库,并从数据库中读取这些字节流以在界面上还原显示。通过处理 FileStream 和 MemoryStream,确保数据准确写入与正确解析。
准备环境与前提条件
操作基于 .NET Framework 环境下的 Windows Forms 应用。你需要:
Visual Studio 开发环境
一个已配置的 SQL Server 数据库实例,且包含接收图片的表(例如名为
table1的表)表单设计器上的控件:用于选择文件的
OpenFileDialog,用于预览/展示的PictureBox,以及必要的按钮控件System.Data.SqlClient命名空间的引用
第1步:获取图片路径并转为字节数组
为了将图片存入数据库,首先需要将其从文件系统读取为二进制格式。以下代码演示了点击事件后的操作流程:
触发文件选择:通过
openFileDialog1.ShowDialog()打开对话框,确认用户选择了有效文件后获取完整路径。初始化 UI 预览:利用
System.Drawing.Image.FromFile(pathName)加载图片并赋值给pictureBox1.Image,以便在保存前进行预览。转换为字节:
- 创建
FileStream对象以只读模式打开该文件。 - 根据文件长度初始化
byte[] buffByte。 - 调用
fs.Read将内容读入数组,随后关闭并释放流资源。
- 创建
private void button2_Click_1(object sender, System.EventArgs e)
{
string pathName;
if (this.openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
pathName = this.openFileDialog1.FileName;
// 1. 读取原图并在界面预览
System.Drawing.Image img = System.Drawing.Image.FromFile(pathName);
this.pictureBox1.Image = img;
// 2. 将图像读入到字节数组
System.IO.FileStream fs = new System.IO.FileStream(pathName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] buffByte = new byte[fs.Length];
fs.Read(buffByte, 0, (int)fs.Length);
fs.Close();
fs = null; // 清空引用
// 3. 建立 Command 命令准备插入
string comm = @"Insert into table1(img, name) values(@img, @name)";
this.sqlCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlCommand1.CommandType = System.Data.CommandType.Text;
this.sqlCommand1.CommandText = comm;
this.sqlCommand1.Connection = this.sqlConnection1;
// 4. 创建 Parameter 参数
// 注意:SQL Server 推荐使用 varbinary(max),旧版代码可能使用 image 类型
this.sqlCommand1.Parameters.Add("@img", System.Data.SqlDbType.Image);
this.sqlCommand1.Parameters["@img"].Value = buffByte;
this.sqlCommand1.Parameters.Add("@name", System.Data.SqlDbType.VarChar);
this.sqlCommand1.Parameters["@name"].Value = pathName.Substring(pathName.LastIndexOf("\\") + 1);
// 5. 执行插入
try
{
this.sqlConnection1.Open();
this.sqlCommand1.ExecuteNonQuery();
this.sqlConnection1.Close();
}
catch (System.Exception ee)
{
MessageBox.Show(ee.Message);
}
buffByte = null;
this.FillListBox(); // 刷新列表或状态
}
}
第2步:从数据库读取图片并显示
当需要从数据库中恢复图片时,需将二进制的 varbinary 或 image 类型字段读取回内存流,进而重建为图像对象。
连接与查询:建立
SqlConnection并执行Select语句获取图片字段数据。流转换:
- 使用
SqlDataReader逐行读取数据。 - 将读取到的字节数据强制转换后传入
MemoryStream。 - 调用
Image.FromStream生成可渲染的 Image 对象。
- 使用
SqlConnection conn = new SqlConnection(@"data source=chenyuming2004VSdotNET;uid=sa;pwd=cym;database=lhf");
conn.Open();
// 注意:生产环境中应避免硬编码密码及明文SQL,建议改用参数化查询
SqlCommand cmd = new SqlCommand("select 照片 from fuser where password='1b'", conn);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
// 将读取的字节数据转换为内存流
MemoryStream buf = new MemoryStream((byte[])reader[0]);
// 从内存流创建图片对象
Image image = Image.FromStream(buf, true);
pictureBox1.Image = image;
注意事项与排错
数据类型兼容性:示例代码中使用了旧的
SqlDbType.Image。在较新的 SQL Server 版本(2005及以上)中,建议使用SqlDbType.VarBinary配合max长度来存储大型二进制数据,以获得更好的性能和未来支持。资源管理:在实际项目中,建议使用
using语句块包裹SqlConnection、SqlCommand、FileStream和MemoryStream,以确保即使发生异常也能自动释放非托管资源。安全性:务必使用参数化查询(如代码中的
@img)来防止 SQL 注入攻击,切勿直接将字符串拼接到 SQL 命令中。
总结
通过上述步骤,你可以实现图片在客户端与 SQL Server 之间的可靠流转。核心在于理解如何将物理文件转化为字节流,以及如何将数据库中的二进制数据还原为图形界面可识别的图像对象。
以上就是C#保存图片到数据库并读取显示图片的详细内容,更多关于C#数据库图片操作的资料请关注本站其它相关文章!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









