How to store and retrieve images in SQL Server database via VB.NET

SQL Server supports the ability to store client objects in tables.

Create a field in which the datatype is Image and initialize the byte array with an initial value of null. Use FileInfo object to get file size. Open FileStream to read the file. Using

+2


source to share


2 answers


Do a little googling before posting here. Below is the third search result I got for your query. I know how to do it, but not enough patience to do it again. So here is some sample code from 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

      

+4


source


An image field in SQL Server is simply an array of bytes. Here's an important code for you. Let's assume that the name of your image field in the database is "imageField". Hope this helps.

To get an image and save it to disk:

//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")

      



To save an image to SQL Server from disk:

''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)

      

+1


source







All Articles