Dynamic thumbnail images from ASP.NET

Dynamic thumbnail images from ASP.NET


Dynamic thumbnail images from ASP.NET Author: Brock Allen
From:
http://staff.develop.com/ballen/blog/

 
i have had this sampe code of dynamic thumbnail generation kicking around for some time, so I've finally gotten the time to post it here. This sample code is an IHttpHandler implementation that reads a JPG from the filesystem and dynamically generates a thumbnail sized version of the image and emits that to the response stream. What I like about this approach is that you don't need to create a file on the filesystem for the thumbnail as it's all done in memory. This really shows how cool (and useful, of course) IHttpHandler is. Here's the gist of the implementation: 

public class ImageHandler : IHttpHandler
{
    // the max size of the Thumbnail
    const int MaxDim = 120; 
    public void ProcessRequest(HttpContext ctx)
    {
        // let's cache this for 1 day
        ctx.Response.ContentType = "image/jpeg";
        ctx.Response.Cache.SetCacheability(HttpCacheability.Public);
        ctx.Response.Cache.SetExpires(DateTime.Now.AddDays(1)); 
        // find the directory where we're storing the images
        string imageDir = ConfigurationSettings.AppSettings["imageDir"];
        imageDir = Path.Combine(
            ctx.Request.PhysicalApplicationPath, imageDir); 
        // find the image that was requested
        string file = ctx.Request.QueryString["File"];
        file = Path.Combine(imageDir, file);
        // load it up
        using (Image img = new Bitmap(file))
        {
            // do some math to resize the image
            // note: i know very little about image resizing,
            // but this just seemed to work under v1.1. I think
            // under v2.0 the images look incorrect.
            // *note to self* fix this for v2.0
            int h = img.Height;
            int w = img.Width;
            int b = h > w ? h : w;
            double per = (b > MaxDim) ? (MaxDim * 1.0) / b : 1.0;
            h = (int)(h * per);
            w = (int)(w * per); 
            // create the thumbnail image
            using (Image img2 =
                      img.GetThumbnailImage(w, h,
                      new Image.GetThumbnailImageAbort(Abort),
                      IntPtr.Zero))
            {
                // emit it to the response strea,
                img2.Save(ctx.Response.OutputStream,
                    System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }
    } 
    public bool IsReusable
    {
        get { return true; }
    } 
    private bool Abort()
    {
        return false;
    }
}
 
This was originally published on Brock Allen's Blog here:

http://staff.develop.com/ballen/blog/

 
brock Allen is an instructor for DevelopMentor where he teaches .NET and ASP.NET. He also manages the ASP.NET curriculum at DevelopMentor by doing research and course development. When not teaching, Brock is an independent consultant doing mentoring, architecture and development work.
 

  (2006-4-05:04:02) 


vb.net版本 
02/08/2006 by
Jeremy Wadsworth


here is the C# code converted to VB.NET. It contains a few minor modifications that are specific to my site. Anyone using either set of code for the Personal Sit Kit will need to modify it to suit their needs. 

<%@ WebHandler Language="VB" Class="Handler" %>

imports System.IO
Imports System.Drawing
Imports System.Drawing.Image
Public Class Handler
Implements IHttpHandler

'the max size of the thumbnail

Const MaxDim As Integer = 120
Dim imagedirectory As String = ""
Dim imagename as String = ""
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable

Get
Return True
End Get

End Property

 

 

Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest

 

With context

If Not .Request.QueryString("Dir") Is Nothing And .Request.QueryString("Dir") <> "" Then
imagedirectory = .Request.QueryString("Dir")
Else
Exit Sub

End If

 

If Not .Request.QueryString("File") Is Nothing And .Request.QueryString("File") <> "" Then
imagename = .Request.QueryString("File")
imagename = imagename.Replace("\", "/")
imagename = imagename.Replace("//", "/")
End If

 

With .Response

.contenttype = "image/jpeg"
.Cache.SetCacheability(HttpCacheability.Public)
.Cache.SetExpires(DateTime.Now.AddDays(1))
End With

'find the image that was requested
Dim file As String = ""
file = imagedirectory &;amp; imagename
file = .Request.MapPath(file)
'load the image
Using img As Image = New Bitmap(file)
'do some math to resize the image 

Dim h As Integer = img.Height
Dim w As Integer = img.Width
Dim b As Integer

If h > w Then
b = h
Else
b = w
End If

Dim per As Double

If b > MaxDim Then
per = ((MaxDim * 1.0) / b)
Else
per = 1.0
End If

h = CType((h * per), Integer)
w = CType((w * per), Integer)

'create the thumbnail image

Using img2 As Image = img.GetThumbnailImage(w, h, New Image.GetThumbnailImageAbort(AddressOf Abort), IntPtr.Zero)
'emit it to the response stream,
img2.Save(.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)

End Using
End Using
End With
End Sub

Private Function Abort() As Boolean
Return False
End Function    (2006-4-05:04:02)

 感谢原创者的辛勤劳动,希望对您有所帮助,转载请注明原出处。
 您可能对 [Asp.Net] 的这些文章也感兴趣:

Assembly学习心得(1)
whats an assembly 什么是assembly
VS.NET 2005 Beta 2初体验(2)-用C 开发Native代码
url传递中文的解决方案
asp.net多频道网站架构实现方法
保护你的代码——谁动了我的组件?
ASP.NET编程中的十大技巧
asp.net中将Excel文件(.xls)绑定到DataGrid
Modal Dialog
如何在 ASP.NET 中创建 OpenID