This is an alternative for "Previewing Image in ASP.NET Image Control"
Introduction
I have already published a tip how to preview the image in ASP.NET image control using C# language. Recently many of them asked me how to achieve this in VB.Net. I asked them to use code converter tool but still many didn't get the appropriate code. So i decided to explain how to achieve the same using VB.NET in this alternative tip
Using the Code
- Create a new website. Add a
FileUpload
control, a button, and an image control. ASPX code:
<table>
<tr>
<td class="style3">
<asp:Label ID="Label1" runat="server" Text="Photo upload" />
</td>
<td class="style4">
<asp:FileUpload runat="server" ID="PhotoUpload" />
</td>
<td class="style4">
<asp:Button runat="server" ID="btnPhotoPreview" Text="Preview" />
</td>
<td class="style1">
<asp:Image runat="server" ID="ImagePreview" Height="164px" Width="125px" />
</td>
</tr>
</table>
- Now add a button click event for
btnPhotopreview
.
<asp:Button runat="server" OnClick="btnPreview_Click" ID="btnPhotoPreview" Text="Preview" />
- We have to add a handler class in order to show the image. We are going to pass
the session variable for FileBytes for the upload control. In the new handler class, get the session
variable and generate the image and the main difference between C# and vb comes here in this part in handling session variables.
Imports System.Web
Imports System.Web.Services
Public Class Handler1
Implements System.Web.IHttpHandler, System.Web.SessionState.IRequiresSessionState
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
If (context.Session("ImageBytes")) IsNot Nothing Then
Dim image As Byte() = DirectCast(context.Session("ImageBytes"), Byte())
context.Response.ContentType = "image/JPEG"
context.Response.BinaryWrite(image)
End If
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
- Now in the button click pass the byte[] in session variable.
Protected Sub btnPhotoPreview_Click(sender As Object, e As EventArgs) Handles btnPhotoPreview.Click
Session("ImageBytes") = PhotoUpload.FileBytes
ImagePreview.ImageUrl = "~/Handler1.ashx"
End Sub
I have attached the source code. It is written in Visual studio 2012, so the solution might not be work with few of your machines. But you can check the class files.