0
Answer

Asp.net c# Upload Images keeping its aspect ratio

Joseph Chong

Joseph Chong

11y
3k
1
Hi all,

I'm new with asp.net c#. Having difficulties in thumbnail fixed size for the resize image.

Below is a example that I want to accomplish. Example #2.
http://www.codeproject.com/Articles/2941/Resizing-a-Photographic-image-with-GDI-for-NET

I did resize the image but only fixed the height to 300. I also need a fixed size thumbnail like the example #2 with color padding.


Below is my code in asp.net c#:

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<%@ Import Namespace="System.Drawing.Drawing2D" %>

protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null)
{
string fileExt = System.IO.Path.GetExtension(FileUpload1.FileName);

if (fileExt == ".jpeg" || fileExt == ".jpg" || fileExt == ".png")
{
string FileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
string FilePath = Server.MapPath("~/CampaignImages/original/" + FileName);
string resizedImage = Server.MapPath("~/CampaignImages/thumb/" + FileName);

//Save files to disk
FileUpload1.SaveAs(FilePath);
Bitmap originalBMP = new Bitmap(FileUpload1.FileContent); 

// Calculate the new image dimensions
int thumbnailSize = 300;
int newWidth, newHeight;

if (originalBMP.Width < originalBMP.Height)
 {
 newWidth = originalBMP.Width * thumbnailSize / originalBMP.Height;
 newHeight = thumbnailSize;
 }
else
 {
 newWidth = thumbnailSize;
 newHeight = originalBMP.Height * thumbnailSize / originalBMP.Width;
 }  
  
// Create a new bitmap which will hold the previous resized bitmap
Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
// Create a graphic based on the new bitmap
Graphics oGraphics = Graphics.FromImage(newBMP);   
oGraphics.Clear(Color.Red);            

// Set the properties for the new graphic file
oGraphics.SmoothingMode = SmoothingMode.AntiAlias;oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
  
// Draw the new graphic based on the resized bitmap
oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);               

// Save the new graphic file to the server
newBMP.Save(resizedImage + FileName ); 

// Once finished with the bitmap objects, we deallocate them.
originalBMP.Dispose(); 
newBMP.Dispose();
oGraphics.Dispose();

else 
 
 LabelError.Text = "File must be in .JPG or .PNG format."; 
 
 
 }


Any help would be appreciate.

Regards,
Joseph