
December 29th, 2006, 07:47 AM
|
 |
Gratefully Deadicated
|
|
Join Date: Sep 2006
Location: The Great Machine
|
|
|
HttpHandler for Images
This sample uses an httpHandler to retrieve an image stored in a sql server database and shows the image on your webform.
The handler I call dataImgHandler:
Code:
<%@ WebHandler Language="VB" Class="dataImgHandler" %>
Imports System
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.IO
Imports System.data
Public Class dataImgHandler : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Try
Dim myImage As Image = GetBitmap(context)
context.Response.ContentType = "image/jpeg"
myImage.Save(context.Response.OutputStream, ImageFormat.Jpeg)
Catch
'If the image field in the database is null, it throws exception
'So, pass the path to the transparent.gif image
Try
Dim req As HttpRequest = context.Request
Dim path As String = req.PhysicalPath
If ((Not (req.UrlReferrer) Is Nothing) AndAlso (req.UrlReferrer.Host.Length > 0)) Then
'load a transparent gif
path = context.Server.MapPath("~/images/transparent.gif")
End If
Dim contentType As String = Nothing
contentType = "image/gif"
context.Response.StatusCode = 200
context.Response.ContentType = contentType
context.Response.WriteFile(path)
Catch
End Try
End Try
End Sub
Private Function GetBitmap(ByVal context As HttpContext) As Bitmap
Dim oBitmap As Bitmap = Nothing
'pass the database guid to get the image row
Dim guid As String = System.Web.HttpContext.Current.Request.QueryString ("guid")
'get the byte data from the image field
Dim myByteImg = 'get data from database here - select imgField1 from mytable where guid = guid
Dim bytPhotoData() As Byte = myByteImg
Dim stmPhotoData As New MemoryStream(bytPhotoData)
oBitmap = Image.FromStream(stmPhotoData)
Return oBitmap
End Function
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return True
End Get
End Property
End Class
And, to get the image into an image control from the code behind aspx.vb page:
Code:
Image1.ImageUrl = "dataImgHandler.ashx?guid=" & guid
I pass a varaible, guid, to let me know what image I need from the database but could have easily used a session.
Happy Coding!
Zath
Last edited by Zath : December 29th, 2006 at 08:38 AM.
Reason: Showed more code to stream image
|