Friday, February 13, 2009

Generate Thumbnail Image View on Fly




One of the common requirement for almost every commercial asp.net web application is how to generate thumbnail view of image on fly.

Example: Generate thumbnail view of product image on fly, if product image is not available in ProductThumbnail Folder and if thumbnail view is already available simply display it rather than generating new thumbnail view.

//Take Original Image Path and Returns Thumbnail Image Path.
private string GetThumbnailView(string originalImagePath,int height,int width)
{
//Consider Image is stored at path like "ProductImage\\Product1.jpg"

//Now we have created one another folder ProductThumbnail to store thumbnail image of product.
//So let name of image be same, just change the FolderName while storing image.
string thumbnailImagePath = originalImagePath.Replace("ProductImage", "ProductThumbnail");
//If thumbnail Image is not available, generate it.
if (!System.IO.File.Exists(Server.MapPath(thumbnailImagePath)))
{
System.Drawing.Image imThumbnailImage;
System.Drawing.Image OriginalImage = System.Drawing.Image.FromFile(Server.MapPath(originalImagePath));
imThumbnailImage = OriginalImage.GetThumbnailImage(width, height,
new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
imThumbnailImage.Save(Server.MapPath(thumbnailImagePath),System.Drawing.Imaging.ImageFormat.Jpeg);

imThumbnailImage.Dispose();
OriginalImage.Dispose();
}
return thumbnailImagePath;
}

public bool ThumbnailCallback() { return false; }

Code to Call Function

GetThumbnailView("ProductImage\\Product1.jpg",100,100);

Reason for Generating Thumbnail: You can display image by simply changing its height and width property, but generating a thumbnail view will decrease page size, therefore transfer of data between server and client, thus pagesize would be light weight and can be load much faster. Summarizing few advantage are Bandwidth Saving, Fast loading (Improved Performance), SEO Friendly, etc.

3 comments:

Unknown said...

Thanks for sharing.

Unknown said...

Nice work!!!
But my question is
can we have dynamic url without aspx extension? IF yes pls guide me

CG said...

How can we do this but preserve the aspect ratio? I'm getting squished photos.

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape