Image in DetailsView part 2
Introduction
In my previous post, we were able to make our DetailsView display our images coming from the database. We were able to do so with the help of an auxilliary web form to display the image, sort of like an image handler. While there's nothing wrong with that technique it requires an extra page to be created just so we can display the image. We can do away with the image handler and let the page draw the image itself.
Post it to me pls
We are going to change the image url /uri of ImageField row from our default page(default.aspx):
DataImageUrlFormatString="~\DisplayPhoto.aspx?emp_no={0}">
to this:
DataImageUrlFormatString="~\Default.aspx?emp_no={0}">
The source will be the page itself; upon loading of the control(DetailsView) it will call itself, this timewith the paramater(emp_no).
Then we're going to move the streaming of image or the drawing of the image to the codebehind of the page itself:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim empNo As String = Request.QueryString("emp_no")
If Not empNo Is Nothing Then
If empNo.Trim <> "" Then
ShowImage(empNo)
End If
End If
End Sub
Private Sub ShowImage(ByVal empNo As String)
Dim commandString As String = "SELECT Photo FROM HR_EmpPhoto WHERE Emp_No=" + empNo.ToString()
Using myConn As New SqlConnection(ConfigurationManager.ConnectionStrings("HissDBConnectionString").ToString())
Dim myCommand As New SqlCommand(commandString, myConn)
myConn.Open()
Dim myReader As SqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
If myReader.Read() Then
Dim imgBuffer As Byte() = CType(myReader.Item("Photo"), Byte())
Response.ContentType = "image/jpeg"
Response.BinaryWrite(imgBuffer)
End If
myConn.Close()
End Using
End Sub
That's all there is to it! You now have an DetailsView which displays images from a database. Pretty easy isn't it?
Notes
Improvements on the technique is to cache the images being displayed so that the application won't need to query for the image . Another thing to note should you use the method ExecuteScalar, it will give you the entire content of the data. While there's nothing wrong with that, getting a huge row size(uncommon for bitmaps) at one time will leave your user unsatisfied with the performance. What we can do is use ExecuteReader and pass the enum parameter SequentialAccess so that it will be given to us as a stream of bytes and use the GetBytes method to access the data into the buffer array.
With the said technique and a combination of GDI+ graphics we can integrated graphical reports to our ASP.NET application. Not just static images but dynamic one, like the ones in Cold Fusion were the report can be graphical and is even animated.
We'll continue with our endeavor into graphics using ASP.NET when we'll create our own CAPTCHA(TM) control using the same technique.