Tuesday, May 24, 2005

Membuat dynamic image thumbnail

public class ImageHandler : IHttpHandler
{ // ukuran maksimal dari Thumbnailnya
const int MaxDim = 120;
public void ProcessRequest(HttpContext ctx) {
ctx.Response.ContentType = "image/jpeg";
ctx.Response.Cache.SetCacheability(HttpCacheability.Public);
ctx.Response.Cache.SetExpires(DateTime.Now.AddDays(1));

// mencari directory dimana imagenya tersimpan
string imageDir = ConfigurationSettings.AppSettings["imageDir"];
imageDir = Path.Combine(ctx.Request.PhysicalApplicationPath, imageDir);

// mencari image yang dicari
string file = ctx.Request.QueryString["File"];
file = Path.Combine(imageDir, file);
// load image
using (Image img = new Bitmap(file)) {
// mengubah ukuran gambar
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);
// membuat thumbnail image
using (Image img2 = img.GetThumbnailImage(w, h,
ew Image.GetThumbnailImageAbort(Abort), IntPtr.Zero))
{
// men-save hasilnya menggunakan response stream
img2.Save(ctx.Response.OutputStream,
System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
public bool IsReusable { get { return true; } }
private bool Abort() { return false; }}

No comments: