Friday, February 10, 2012

Image resize in asp.net and c#

protected void UploadFile(Object s, EventArgs e)
{
// First we check to see if the user has selected a file
if (fileUpload.HasFile)
{
// Find the fileUpload control
string filename = fileUpload.FileName;

// Check if the directory we want the image uploaded to actually exists or not
if (!Directory.Exists(MapPath(@"Uploaded-Files")))
{
// If it doesn't then we just create it before going any further
Directory.CreateDirectory(MapPath(@"Uploaded-Files"));
} 

// Specify the upload directory
string directory = Server.MapPath(@"Uploaded-Files\"); 

// Create a bitmap of the content of the fileUpload control in memory
Bitmap originalBMP = new Bitmap(fileUpload.FileContent); 

// Calculate the new image dimensions
int origWidth = originalBMP.Width; 
int origHeight = originalBMP.Height;
int sngRatio = origWidth / origHeight; 
int newWidth = 100;
int newHeight = newWidth / sngRatio; 

// 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); 

// 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(directory + "tn_" + filename); 

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

// Write a message to inform the user all is OK
label.Text = "File Name: " + filename + "
"; 
label.Text += "Content Type: " + fileUpload.PostedFile.ContentType + "
";
label.Text += "File Size: " + fileUpload.PostedFile.ContentLength.ToString() + "";
// Display the image to the user
Image1.Visible = true;
Image1.ImageUrl = @"/Uploaded-Files/tn_" + filename; 
}
else
{
label.Text = "No file uploaded!"; 
}
}

1 comment: