<asp:Image ID="img" runat="server" ImageUrl="~/Desert.jpg?size=64" /> <asp:Image ID="Image1" runat="server" ImageUrl="~/Desert.jpg?size=164" /> <asp:Image ID="Image2" runat="server" ImageUrl="~/Desert.jpg?size=364" />
Here, you can see, I have passed sizes in querystring. Size=64 means I am requesting 64x64 size of that image. Now the next step is to make “ResizeImageHandler”. I am resizing image on the fly, means not storing anywhere. Just resizing image and throwing back to the response.
Note: requested image "Desert.jpg" must exist on your server, otherwise it will throw exception. I haven't handled exception because this is just example to understand IHttpHandler
Imports System.Drawing Imports System.IO Public Class ResizeImageHandler Implements IHttpHandler Public ReadOnly Property IsReusable As Boolean Implements IHttpHandler.IsReusable Get Return True End Get End Property Public Sub ProcessRequest(context As HttpContext) Implements IHttpHandler.ProcessRequest Dim req As HttpRequest = context.Request Dim res As HttpResponse = context.Response 'Get the image file path ' Dim path As String = req.PhysicalPath 'Get the Image ' Dim img As Image = Image.FromFile(path) 'Image converter ' Dim converter As New ImageConverter Dim s As Size If req.QueryString("size") IsNot Nothing Then 'Get the size to Resize original image ' Dim sz As String = req.QueryString("size") s = New Size(sz, sz) 'Resize the original image to requested size ' Dim bm As Bitmap = New Bitmap(img, s) 'Convert to Image ' Dim fImg As Image = bm 'Write the Resized Image to browser ' res.BinaryWrite(converter.ConvertTo(fImg, GetType(Byte()))) Else 'Write the original image ' res.BinaryWrite(converter.ConvertTo(img, GetType(Byte()))) End If End Sub End Class
Now, after creating class which implements IHttpHandler, we have to register it. I am using IIS 7 with Integrated Mode, so I have registered as below. There are different ways to register the Handler based on which IIS you are using and in which mode (classic/Integrated).
To know, which registration method you have to use, read this MSDN Article
<configuration> <system.webServer> <handlers> <add name="ResizeImageHandler" verb="GET" path="*.jpg" type="ResizeImageHandler" resourceType="Unspecified" /> </handlers> </system.webServer> </configuration>
Now it’s time to run the page with above Image server controls. After running that page, you will see following output.
No comments:
Post a Comment