SQL Server 2000Windows VistaDBAWindows 2003Visual Studio 2008.NET 3.0Visual Studio 2005ADO.NETWindows 2000Windows XP.NET 2.0.NET 3.5SQL Server 2005C# 2.0C# 3.0中级开发Visual StudioSQL ServerSQLWindows.NETC#
在 SQL Server 中存储或保存图像
一个演示如何将图像保存或存储到 SQL Server 的示例程序。
引言
此示例代码说明了如何在 SQL Server 数据库中存储图像。它使用 ADO.NET System.Data.SqlClient
命名空间。可以使用 SQL 参数将图像存储在 SQL Server 中。
![]() |

如何在 SQL Server 表中存储图像
要将图像存储到 SQL Server 中,您需要将图像文件读取到字节数组中。一旦您在字节数组中有了图像数据,您就可以使用 SQL 参数轻松地将此图像数据存储在 SQL Server 中。以下代码解释了如何执行此操作
private void cmdSave_Click(object sender, EventArgs e)
{
try
{
//Read Image Bytes into a byte array
byte[] imageData = ReadFile(txtImagePath.Text);
//Initialize SQL Server Connection
SqlConnection CN = new SqlConnection(txtConnectionString.Text);
//Set insert query
string qry = "insert into ImagesStore
(OriginalPath,ImageData) values(@OriginalPath, @ImageData)";
//Initialize SqlCommand object for insert.
SqlCommand SqlCom = new SqlCommand(qry, CN);
//We are passing Original Image Path and
//Image byte data as SQL parameters.
SqlCom.Parameters.Add(new SqlParameter("@OriginalPath",
(object)txtImagePath.Text));
SqlCom.Parameters.Add(new SqlParameter("@ImageData", (object)imageData));
//Open connection and execute insert query.
CN.Open();
SqlCom.ExecuteNonQuery();
CN.Close();
//Close form and return to list or images.
this.Close();
}
以下代码解释了如何将图像文件读取到字节数组中
//Open file in to a filestream and read data in a byte array.
byte[] ReadFile(string sPath)
{
//Initialize byte array with a null value initially.
byte[] data = null;
//Use FileInfo object to get file size.
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;
//Open FileStream to read file
FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
//Use BinaryReader to read file stream into byte array.
BinaryReader br = new BinaryReader(fStream);
//When you use BinaryReader, you need to supply number of bytes
//to read from file.
//In this case we want to read entire file.
//So supplying total number of bytes.
data = br.ReadBytes((int)numBytes);
return data;
}
如何从 SQL Server 表中读取图像数据
要从 SQL Server 读取图像,首先准备一个数据集,它将保存来自 SQL Server 表的数据。将此 数据集
绑定到窗体上的 gridview
控件。
void GetImagesFromDatabase()
{
try
{
//Initialize SQL Server connection.
SqlConnection CN = new SqlConnection(txtConnectionString.Text);
//Initialize SQL adapter.
SqlDataAdapter ADAP = new SqlDataAdapter("Select * from ImagesStore", CN);
//Initialize Dataset.
DataSet DS = new DataSet();
//Fill dataset with ImagesStore table.
ADAP.Fill(DS, "ImagesStore");
//Fill Grid with dataset.
dataGridView1.DataSource = DS.Tables["ImagesStore"];
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
一旦您在网格中有了图像数据,从网格单元格中获取图像数据。或者,您也可以从 数据集
表单元格中获取图像数据。
//When user changes row selection, display image of selected row in picture box.
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
try
{
//Get image data from gridview column.
byte[] imageData =
(byte[])dataGridView1.Rows[e.RowIndex].Cells["ImageData"].Value;
//Initialize image variable
Image newImage;
//Read image data into a memory stream
using (MemoryStream ms = new MemoryStream(imageData, 0, imageData.Length))
{
ms.Write(imageData, 0, imageData.Length);
//Set image variable value using memory stream.
newImage = Image.FromStream(ms, true);
}
//set picture
pictureBox1.Image = newImage;
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
如果需要,您可以扩展此代码以将图像从 PictureBox 保存到本地图像文件。
//Store image to a local file.
pictureBox1.Image.Save("c:\test_picture.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
关注点
如果您在设计模式下看到 frmImageStore
,我已将 picturebox1
放置在一个 panel
中。此面板的 AutoScroll
属性设置为 True
,并且 PictureBox1
的 SizeMode
属性设置为 True
。这允许 picturebox
调整自身大小以适应原始图片的大小。当 picturebox
的大小大于 Panel1
的大小时,Panel
的滚动条将变为活动状态。
如何下载和运行程序
- 从我的网站下载源代码 zip 文件 http://www.shabdar.org 并解压缩它。
- 从 SQL 数据库 文件夹中还原数据库。
- 如果由于某种原因无法还原提供的数据库,您可以使用 SQL 数据库 目录中提供的脚本生成必要的表。
- 打开解决方案并在
frmImagesStore
窗体上更改连接字符串。
要求
- Visual Studio .NET 2005
- .NET Framework 2.0
- Microsoft SQL Server 2000 数据库或 Microsoft SQL Server 2005 数据库