Create High Quality Thumbnail - Resize Image Dynamically - ASP .Net C# Code

This article will help you create high quality thumbnail from an image as well as resize image dynamically.

GetThumbnailImage method of class Bitmap produces a thumbnail image from the file specified. Life is so easy with it. Not always though. Sometimes the thumbnail produced has low quality - pixelated and blurred.

Why it Happens? Why My Images are Pixelated and Blurred?

Image formats like jpeg may store the thumbnail inside the same file. If we use System.Drawing.Bitmap method GetThumbnailImage, method checks if there’s a thumbnail image stored into the file and, if the thumb is found, it returns that thumbnail version scaled to the width and height you requested. If the thumbnail version of the image is smaller then the size you requested to produce, thats when problem occurs. The thumbnails produced become pixelated as we know stretching an image to a larger once reduces the Image Quality.

Solution:

Solution is really simple. We will load the source image to a System.Drawing.Image object, scale it to the desired width and height preserving good quality and save it to a new file.

Step by Step Procedure to Create a Good Quality Thumbnail:

For this example lets assume these variables

String src="c:/myImages/a.jpg";   //absolute location of source image

String dest="c:/myImages/a_th.jpg";    //absolute location of the new image created(thumbnail)

int thumbWidth=132;    //width of the image (thumbnail) to produce

The code snippest shown here is in ASP .NET C#.

You have to use these namespaces

using System.Drawing; 

using System.Drawing.Drawing2D;

Following are the Steps along with example code:

- Get the source image to a System.Drawing.Image object
System.Drawing.Image image = System.Drawing.Image.FromFile(src); 


-  Create a System.Drawing.Bitmap with the desired width and height of the thumbnail. 
int srcWidth=image.Width;
int srcHeight=image.Height; 

//we will get the sizeratio in decimal so that we dont get exception in case width is less then height.

Decimal sizeRatio = ((Decimal)srcHeight/srcWidth);
int thumbHeight=Decimal.ToInt32(sizeRatio*thumbWidth);
Bitmap bmp = new Bitmap(thumbWidth, thumbHeight);


- Create a System.Drawing.Graphics object from the Bitmap which we will use to draw the high quality scaled image
System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);


- Set the System.Drawing.Graphics object property SmoothingMode to HighQuality
gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;


- Set the System.Drawing.Graphics object property CompositingQuality to HighQuality
gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;


- Set the System.Drawing.Graphics object property InterpolationMode to High
gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;


- Draw the original image into the target Graphics object scaling to the desired width and height
System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, thumbWidth, thumbHeight);
gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);


- Save to destination file
bmp.Save(dest);


- dispose / release  resources
bmp.Dispose();
image.Dispose();           

Lets help each other:

I get emails often asking for help with the code. I always love to do that. Unfortunately sometimes I get too busy. I have a full-time job, maintain two sites, and married. If you have problems with this code, please post on the comment. Anybody interested helping others may reply on the comments as well.

Resources:

http://www.WebCosmo.com 100% Free Classified Advertising 

Free Advertising on our website www.WebCosmo.com  for jobs, apartments, personals, pets and much more in more then 30 countries.

Currently rated 4.7 by 7 people

  • Currently 4.714286/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by: Manik
Posted on: 10/19/2007 at 6:37 AM
Tags:
Categories: Programming / Coding
E-mail |  Stumble it! |  Propeller it! |  Digg it! |  del.icio.us |  Technorati
Post Information: Permalink | Comments (20) | Post RSSRSS comment feed

Related posts

Comments

WebCosmo us

Friday, December 21, 2007 3:46 PM

WebCosmo

Comments open on this blog entry.

sam in

Monday, January 07, 2008 7:57 AM

sam

This man for such a brilliant code. I have tried many codes but they either change the width or height. I want thumbnails of a specific heigth and width so that my layout won't break and the pics don't get pixalized. All credit goes to you. Good work. Hats off. =)

Thanks. =)

Arun us

Wednesday, January 16, 2008 10:14 PM

Arun

hi,

i found your article really useful. i got my image resized to thumb.
But i can't display the resized thumb into a image control

Imrankhan in

Wednesday, January 16, 2008 11:40 PM

Imrankhan

Hey there.
I have one problem regarding to generate text image with specify height and width.
Actually I am working on Image Editor in which you can generate text image and also you can resize it by using gragsize functionalities.My problem is that when I scratch text image,it lost quality.Suppose I scratch image as width=500 and height as 100 then generated text lost quality.My question is that Can I draw text in specify rectangle with the 100% hieght and width.I mean if I set rectangle height=100 and width=500,Can we draw text in this area.Text should be shown as scratches image.
Thanks in advance

WebCosmo us

Thursday, January 17, 2008 3:42 AM

WebCosmo

Arun,
When you save the image you save it by absolute URL. To show it on image control you have to do it by relative url.
For example lets say you saved it as C:/inetpub/wwwroot/MyWebsite/img/myimage.gif
To show the image on a image control you do it like this <asp:image id="img" runat="server" ImageUrl="~/img/myimage.gif" />
~ will find the image folder relative to the root of your website folder.


WebCosmo us

Thursday, January 17, 2008 3:44 AM

WebCosmo

ImranKhan,
If you stretch image then it will loose quality. You can only make images smaller maintaining quality. If you make it bigger then the original it will loose quality.

Gunnar ee

Sunday, February 17, 2008 8:11 AM

Gunnar

You have one bad line in your example that throws exception when thumbnails's width is bigger than it's height:

int thumbHeight=(srcHeight/srcWidth)*thumbWidth;

Use this code instead:

int thumbHeight=(srcHeight*thumbWidth)/srcWidth;

to avoid rounding errors.

Pareen Vatani in

Wednesday, February 27, 2008 4:48 AM

Pareen Vatani

AWESOME DUDE

pravin in

Wednesday, March 05, 2008 8:08 AM

pravin

Really nice approach!!

but i want to resize image in specified height width.

if any solution then post it to me.


I will be really grate full

WebCosmo us

Wednesday, March 05, 2008 9:22 AM

WebCosmo

Pravin,
You could use the same approach for specific width and height.
Take off this line
int thumbHeight=(srcHeight/srcWidth)*thumbWidth;

instead use:
int thumbWidth=520; //520 as example
int thumbHeight=650; //650 as example
Hope that helps.

Soren Berghall se

Friday, March 21, 2008 4:31 AM

Soren Berghall

Excellent! 5!

Nick gb

Wednesday, March 26, 2008 2:02 PM

Nick

Awesome! Exactly what I was looking for.

Thank you.

Linc cn

Tuesday, May 13, 2008 11:07 PM

Linc

Thanks to your code,it help me a lot,I'll trans into chinese.I cann't find any Chinese version.
thx very much!!!

HuuLe vn

Friday, June 13, 2008 10:40 PM

HuuLe

thanks alot about title "Create High Quality Thumbnail - Resize Image Dynamically - ASP .Net C# Code".

Le

Kristoffer dk

Monday, June 23, 2008 11:30 PM

Kristoffer

Thank you. The code helped me a lot.

saeed il

Friday, June 27, 2008 4:58 AM

saeed

hi thanks for the code

i have this problem point to line 23

what i have miss ?

Compiler Error Message: CS0246: The type or namespace name 'Bitmap' could not be found (are you missing a using directive or an assembly reference?)

Source Error:



Line 21: Decimal sizeRatio = ((Decimal)srcHeight/srcWidth);
Line 22: int thumbHeight=Decimal.ToInt32(sizeRatio*thumbWidth);
Line 23: Bitmap bmp = new Bitmap(thumbWidth, thumbHeight);
Line 24: System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
Line 25: gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

WebCosmo us

Friday, June 27, 2008 5:09 AM

WebCosmo

Saeed,
You need to use these namespaces to get rid of that error.

using System.Drawing.Imaging;
using System.Drawing;

Justin au

Monday, July 07, 2008 1:17 AM

Justin

Just wanted to say thanx for this excellent piece of code.

Works a treat!

filippo ITALY it

Thursday, July 24, 2008 12:59 AM

filippo ITALY

Grazie per il POST, veramente utile e semplice la spiegazione della Thumbnail
thk

ciao

jayahari in

Thursday, August 07, 2008 2:23 AM

jayahari

nice code.but i hve some doubts on this.
i have used this code to resize an image while uploading to server.i use to collect the image from the fileupload control and after resizing i use to giv the destination path to save the resized image.
it works fine in local system.bt problem was when i uploaded the application.it was nt working.i mean the bmp.save(dest) was not working.can u please help me wth this issue
thx

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

Sunday, September 07, 2008 2:57 PM