The web browser needs to access resources, like an image, using a URL.
For example:
-
<asp:Image ImageUrl="http://localhost/myimage.jpg" />
But since your image is stored in a database, there is no URL to the image.
To get around this problem you should create an ASPX page that will retrieve the image from the database and return it (in it's binary form) to the browser instead of HTML (which is what the ASPX page would normally return).
- Add an ASPX page called "Thumbnail.aspx" to your website for this purpose.
- In the Page Load event:
- Change the content-type that is part of "header" to indicate that you are returning an image
- Retrieve the ID of the image from QueryString, Cookies, or Session (depending on how you are passing the ID of the image to this ASPX page)
- Retrieve the image from the database and write that to the Response.Output stream
-
Public Partial Class Thumbnail
-
Inherits System.Web.UI.Page
-
Protected Sub Page_Load(sender As Object, e As EventArgs)
-
-
'Changing the ContentType from HTML to image/jpg
-
Response.ContentType = "image/jpg"
-
-
'Retrieving the Image ID from the QuerytString
-
Dim id As As Integer
-
Integer.TryParse(Request.QueryString("ID"), id)
-
-
'Connecting to the database and retrieving the image
-
'The connection string is stored in the web.config file...
-
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ImageDatabaseConnectionString").ConnectionString
-
-
Dim dbCon As SqlConnection
-
dbCon = New SqlConnection(connectionString)
-
Dim sqlCom As New SqlCommand
-
sqlCom.Connection = dbCon
-
sqlcom.CommandType = CommandType.Text
-
sqlCom.CommandText = "SELECT image FROM IMAGES " _ +
-
"WHERE ID=@ImageID"
-
sqlCom.Parameters.Add("@ImageID", SqlDbType.Int).Value = id
-
-
Try
-
-
dbCon.Open()
-
Dim imgContents As Byte() = DirectCast(sqlcom.ExecuteScalar(), Byte())
-
-
'Now that we have the image, writing it to the Response's Output Stream
-
Response.BinaryWrite(imgContents)
-
-
Catch ex As Exception
-
'Something went wrong connecting to the Database
-
Finally
-
'Ensuring that the database connection is closed
-
'Even if something went wrong
-
dbCon.Close()
-
End Try
-
End Sub
-
End Class
So now you have an ASPX page that returns an image in the form of a Byte Array to the browser.
You can now use the URL to this page as the "ImageSource" of an ASP.NET Image control to display the Image that is returned. All you have to do is make sure to pass the ID of the image you want to retrieve through the query string using the URL (because that's what this example is using...but you could use Session or Cookies or whatever you please)
Like this:
-
<asp:Image ImageUrl="http://localhost/Thumbnail.aspx?id=4" />
-Frinny