Search This Blog

Friday, July 30, 2010

Fetching image from database in ASP.NET

In asp database the images are stored in form of binary array.So it is never easy to fetch the image and display it in a image control.For doing so we take a round about method where we print the image in a page and ten we direct the image url in the image control to that page.

Next we would follow the steps to do that :

Now we shall add a page named image.aspx and in the image.aspx.vb we shall write the code given below


Partial Class image
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim s As String = Request.QueryString("val")
Try
con.Open()
com.CommandText = "select * from items where pid ='" & s & "'"
com.Connection = con
dr = com.ExecuteReader
dr.Read()
Dim bytImage As Byte() = New Byte() {}
bytImage = dr.Item(7)
Response.ContentType = "image/jpeg"
Response.Expires = 0

Response.Buffer = True

Response.Clear()
Response.BinaryWrite(bytImage)
Response.End()

Catch ex As Exception

MsgBox(ex.Message)

Finally
con.Close()
com.Cancel()
dr.Close()

End Try
End Sub

End Class



In this page we will get the image from the database an a binary form and will binarywrite the image in this page.We shall get the pid from the querystring which we shall pass from the page where the image control is. In that page we will direct the image url as below :

Image1.ImageUrl = "~/image1.aspx?vall=" & DropDownList1.SelectedValue

where dropdownlist1.selected value returns a element of the pid coloum in the items table
I have already shown how to connect the database using the module in my earlier blog

No comments:

Post a Comment