For this task we use some library and method.
Steps:
- Create a sample ASP.NET Website, add new web form.
- Paste the below design code into aspx page.
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:FileUpload ID="FileUpload1" runat="server" />
- <br />
- <asp:Button ID="Button1" runat="server" Text="Upload" onclick="Button1_Click" />
- <br />
- <!-- To display the Size of image -->
- <span>Size Before Resize : </span>
- <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
- <br />
- <span>Size After Resize : </span>
- <asp:Label ID="Label2" runat="server" Text=""></asp:Label>
- <br />
- <!-- To display the Resize Image -->
- <asp:Image ID="Image1" runat="server" />
- </div>
- </form>
- </body>
- </html>
- Now use the following code into Button1_Click event on aspx.cs page:
- protected void Button1_Click(object sender, EventArgs e)
- {
-
- if (FileUpload1.PostedFile != null)
- {
-
- string extension = Path.GetExtension(FileUpload1.FileName);
- if (extension.ToLower() == ".png" || extension.ToLower() == ".jpg")
- {
- Stream strm=FileUpload1.PostedFile.InputStream;
- using (var image = System.Drawing.Image.FromStream(strm))
- {
-
- Label1.Text = image.Size.ToString();
- int newWidth = 240;
- int newHeight = 240;
- var thumbImg = new Bitmap(newWidth, newHeight);
- var thumbGraph = Graphics.FromImage(thumbImg);
- thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
- thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
- thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
- var imgRectangle = new Rectangle(0, 0, newWidth, newHeight);
- thumbGraph.DrawImage(image, imgRectangle);
-
- string targetPath = Server.MapPath(@"~\Images\") + FileUpload1.FileName;
- thumbImg.Save(targetPath, image.RawFormat);
-
- Label2.Text = thumbImg.Size.ToString();
-
- Image1.ImageUrl = @"~\Images\" + FileUpload1.FileName;
- }
- }
- }
- }
Note: Before using above code you must use the Following Namespace:
- using System.Drawing;
- using System.Drawing.Drawing2D;
- using System.IO;
- Now run the website and upload and image.
Thanks for reading.