The following code describe how to save an image file into SQL Server database. In the first code So, first take the image from the file in FileStream then convert into byte array. After that this byte array passes to the sql query as a parameter and then executes the SQL Command that insert the byte array in the image type SQL column.
Function for converting image into Byte array
Private Sub FindImageInByte() Dim oFile As System.IO.FileInfo oFile = New System.IO.FileInfo(Filename) Dim oFileStream As System.IO.FileStream = oFile.OpenRead() Dim lBytes As Long = oFileStream.Length If (lBytes > 0) Then Dim fileData(lBytes - 1) As Byte oFileStream.Read(fileData, 0, lBytes) oFileStream.Close() SaveToDB(fileData) End If End Sub
Function for saving image in the form Byte() into sql table
Private Sub SaveToDB(ByVal memStreamOrg As Byte()) Dim sqlConn As New SqlClient.SqlConnection sqlConn.ConnectionString = "Put your connection string" sqlConn.Open() Dim Command As New SqlClient.SqlCommand("Insert into tblImage (Image_Temp) values( @PicOrig )", sqlConn) Dim PicOrig As SqlClient.SqlParameter PicOrig = New SqlClient.SqlParameter("@PicOrig", SqlDbType.Image) PicOrig.Value = memStreamOrg Command.Parameters.Add(PicOrig) Command.ExecuteNonQuery() sqlConn.Close()
Note: ntext , text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.