Home > front end >  Loading Images on HTML Asynchronously using MVC
Loading Images on HTML Asynchronously using MVC

Time:09-08

I need to implement a Web Page with a Profile Picture of the user. However, the loading of the picture from the database takes about 2 seconds to load completely.

I need to put a GIF with Circle Animation while the Profile Picture is loading.

enter image description here

Then, once the Database has completely replied back with the image, it should change the GIF image to the User's Profile Picture.

enter image description here

Here is the controller:

  <HttpGet>
        Public Async Function ProfilePicture(ByVal UserId As Integer) As Task(Of ActionResult)
            Using oUser As New User
                oUser.UserID = UserId
                Dim oData As Byte() = Await oUser.RetrievePicFromDb
                If oData IsNot Nothing AndAlso oData.Length > 0 Then
                    Return File(oData, "image/jpg", "")
                Else
                    Return File("~/Content/Images/default-profile.png", "image /jpg", "")
                End If
            End Using
        End Function

Here is the data retrieval from the database

Public Async Function RetrievePicFromDb() As Task(Of Byte())
        Dim b As Byte()
        Try
            Using cn As New SqlClient.SqlConnection
                cn.ConnectionString = ConfigurationManager.ConnectionStrings("SQLServer").ConnectionString
                cn.Open()
                Dim oCmd As New SqlClient.SqlCommand
                oCmd.Connection = cn
                oCmd.CommandType = CommandType.Text

                oCmd.Parameters.Clear()
                oCmd.Parameters.AddWithValue("@UserID", UserID)

                oCmd.CommandText = "Select Picture From Users Where UserID = @UserID"
                Dim iCol As Integer = 0
                Dim oReader As SqlClient.SqlDataReader = oCmd.ExecuteReader
                oReader.Read()
                Dim bImageByte(oReader.GetBytes(iCol, 0, Nothing, 0, Integer.MaxValue) - 1) As Byte
                oReader.GetBytes(iCol, 0, bImageByte, 0, bImageByte.Length)
                Dim ms As New System.IO.MemoryStream(bImageByte)
                Using ms
                    Dim jpgMS = New System.IO.MemoryStream
                    Dim jpgImage As System.Drawing.Image = System.Drawing.Image.FromStream(ms)

                    jpgImage.Save(jpgMS, System.Drawing.Imaging.ImageFormat.Jpeg)
                    b = jpgMS.ToArray()
                End Using
                oReader.Close()
                cn.Close()
            End Using
            Return b
        Catch ex As Exception
            Return Nothing
        End Try
    End Function

An warning error is being generated:

enter image description here

and the displayed picture is

enter image description here

Any amount of help is appreciated!

Thanks!

CodePudding user response:

Try to use this await Task.Run(() => @Your synchronous function);

  • Related