Hey guys and gals,
I have been looking for a solution for this all over the web and it took me a couple of hours to figure it out. Finally I did it. So, here's my code to upload a picture file using the fileupload control, resize the file and then store it to a SQL Server database.
If FleUpload.HasFile Then
Dim fileName As String = Server.HtmlEncode(FleUpload.FileName)
Dim extension As String = System.IO.Path.GetExtension(fileName)
If (extension.ToUpper = ".JPG") Or (extension.ToUpper = ".GIF") Then
'**** Resize image section ****
Dim image_file As System.Drawing.Image = System.Drawing.Image.FromStream(FleUpload.PostedFile.InputStream)
Dim image_height As Integer = image_file.Height
Dim image_width As Integer = image_file.Width
Dim max_height As Integer = 120
Dim max_width As Integer = 160
image_height = (image_height * max_width) / image_width
image_width = max_width
If image_height > max_height Then
image_width = (image_width * max_height) / image_height
image_height = max_height
Else
End If
Dim bitmap_file As New Bitmap(image_file, image_width, image_height)
Dim stream As New System.IO.MemoryStream
bitmap_file.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg)
stream.Position = 0
Dim data(stream.Length) As Byte
stream.Read(data, 0, stream.Length)
'**** End resize image section ****
Dim myConn As New SqlConnection(ConfigurationManager.ConnectionStrings("cs").ConnectionString)
Dim mycmd As New SqlCommand("se_equipmentimages_insert", myConn)
mycmd.CommandType = CommandType.StoredProcedure
mycmd.Parameters.AddWithValue("@equipment_id", id)
mycmd.Parameters.AddWithValue("@image_file", data)
Try
myConn.Open()
mycmd.ExecuteNonQuery()
Catch ex As Exception
Finally
myConn.Close()
End Try
Else
lblError.Text = "Please only upload .jpg or .gif files"
lblError.Visible = True
End If
Else
lblError.Text = "No file selected"
lblError.Visible = True
End If
I hope this helps someone!