如何通过VB.NET在sql server数据库中存储和检索图像
问题描述:
SQL Server支持客户端在表格中存储 对象的功能。如何通过VB.NET在sql server数据库中存储和检索图像
创建字段的数据类型的图像和初始化一个空值initially.Use FileInfo对象的字节数组获取文件size.Open的FileStream读取文件。使用
答
在这里发帖之前做一点谷歌搜索。以下是我为您查询得到的第三个搜索结果。我知道如何做到这一点,但没有足够的耐心再做一次。因此,这里是从TechArena
Function SaveImage _ (ByVal FileName As String) As Integer ' Create a FileInfo instance ' to retrieve the files information Dim fi As New FileInfo(FileName) ' Open the Image file for Read Dim imgStream As Stream = _ fi.OpenRead ' Create a Byte array the size ' of the image file for the Read ' methods buffer() byte array Dim imgData(imgStream.Length) As Byte imgStream.Read(imgData, 0, fi.Length) Dim cn As New SqlConnection _ (ConfigurationSettings.AppSettings("cn")) Dim cmd As New SqlCommand("Images_ins", cn) cmd.CommandType = CommandType.StoredProcedure With cmd.Parameters .Add("@FileName", VarChar, 100).Value = _ fi.Name .Add("@FileType", VarChar, 10).Value = + fi.Extension .Add("@Image", Image).Value = imgData .Add("@FileSize", Int, 4).Value = fi.Length End With cn.Open() cmd.ExecuteNonQuery() cn.Close() cn.Dispose() End Function
答
在SQL Server中的图像字段中的示例代码是一个简单的字节数组。这是您需要的重要代码。假设数据库中图像字段的名称是“imageField”。希望这可以帮助。
要检索图像并将其保存到磁盘:
//dr is a DataReader returned from a SELECT command
Dim imageInBytes As Byte() = dr("imagefield")
Dim memoryStream As System.IO.MemoryStream = _
New System.IO.MemoryStream(imageInBytes, False)
Dim image As System.Drawing.Image = _
System.Drawing.Image.FromStream(memoryStream)
image.Save("c:\image")
要保存图像到SQL Server从磁盘:
''Get the image file into a Byte Array
Dim image As Byte() = System.IO.File.ReadAllBytes("c:\image.jpg")
''Add the byte array as a parameter to your Insert/Update SQLCommand
parameters.Add("@ImageField", image)