Resize image the time of uploading using asp.net
<form id="form1" runat="server">
<asp:FileUpload ID="fileUpload" runat="server" />
<br /><br />
<asp:Button ID="uploadButton" runat="server" Text="Upload!" OnClick="UploadFile" />
<br /><br />
<asp:Label ID="label" runat="server"></asp:Label> <br /><br />
<asp:Image ID="Image1" ImageUrl="" runat="server" Visible="false" />
</form>
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(@"images")))
{
// If it doesn't then we just create it before going any further
Directory.CreateDirectory(MapPath(@"images"));
}
// Specify the upload directory
string directory = Server.MapPath(@"images\");
// 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: <b style='color: red;'>" + filename + "</b><br>";
label.Text += "Content Type: <b style='color: red;'>" + fileUpload.PostedFile.ContentType + "</b><br>";
label.Text += "File Size: <b style='color: red;'>" + fileUpload.PostedFile.ContentLength.ToString() + "</b>";
// Display the image to the user
Image1.Visible = true;
Image1.ImageUrl = @"/images/tn_" + filename;
}
else
{
label.Text = "No file uploaded!";
}
}
Comments
Post a Comment