Wednesday, 23 January 2013 14:51

how to resize or make thumbnail image in asp.net

Written by 
Rate this item
(0 votes)

by the following way you can resize a image to a predefined
dimension and resolution.you can also use it to make a image
thumbnails.

here the thumbnail dimension will be 125x100.the dimension
may not be accurate normally because there is width or height
reduction according to portrait or landscape image for maintaining
image aspect ratio.

you can use the following codes to achieve image resizing
efficiently.i used it in my application.

String upName = null;
const int bmpH = 100;
const int bmpW = 125;

Int32 newWidth = bmpW;
Int32 newHeight = bmpH;
string filePath = "";

// any path where the file will be saved
filePath = Server.MapPath(subPath + "\\" + User_Name) + "\\" + ImageName; //main image path to be saved

Bitmap upBmp = (Bitmap)Bitmap.FromStream(fileUpload.PostedFile.InputStream);
Double upWidth = upBmp.Width;
Double upHeight = upBmp.Height;
Double reDuce = 0;
if (upWidth > upHeight)
{
//Landscape picture
reDuce = newWidth / upWidth;
newHeight = ((Int32)(upHeight * reDuce));

}
else if (upWidth < upHeight)
{
//Portrait picture
reDuce = newHeight / upHeight;
newWidth = ((Int32)(upWidth * reDuce));
}

else if (upWidth == upHeight)
{
//square picture
reDuce = newHeight / upHeight;
newWidth = ((Int32)(upWidth * reDuce));

}
Bitmap newBmp = new Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);//new
newBmp.SetResolution(96, 96);
Graphics newGraphic = Graphics.FromImage(newBmp);
try
{
newGraphic.Clear(Color.White);
newGraphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
newGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
newGraphic.CompositingQuality = CompositingQuality.HighQuality;//new
newGraphic.DrawImage(upBmp, 0, 0, newWidth, newHeight);
newBmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch { }
finally { upBmp.Dispose(); newBmp.Dispose(); newGraphic.Dispose(); }

good luck........

Read 1781 times
Super User

Email This email address is being protected from spambots. You need JavaScript enabled to view it.
Login to post comments