Resizing Images In ASP.NET
I’m sure there are plenty of similar topics out there but this is my two cents. Lets say you have the following code in your ASP.NET page:
1 Upload a File: <asp:FileUpload ID="pictureUpload" runat="server" /><br />
2 <asp:Button ID="btnUpload" runat="server" Text="Upload" OnCommand="handle_ButtonClick" CommandName="Upload" />
Let’s look at the event handler code that uploads the image to the server and resizes it.
1 protected void handle_ButtonClick(object sender, CommandEventArgs e)
2 {
3 if (e.CommandName == "Upload")
4 {
5 if (pictureUpload.HasFile)
6 {
7 string FilePath = HttpContext.Current.Server.MapPath(PATH_FILESFOLDER) + pictureUpload.FileName;
8 pictureUpload.SaveAs(FilePath);
9 ResizeImageAndSave(FilePath, 90);
10 }
11 }
12 }
13
14 public void ResizeImageAndSave(string FilePath, int Width)
15 {
16 Bitmap loBMP = new Bitmap(FilePath);
17 ImageFormat loFormat = loBMP.RawFormat;
18
19 //*** If the image is smaller than a thumbnail just return it
20 if (loBMP.Width < Width) return;
21
22 decimal lnRatio = Convert.ToDecimal(Width) / loBMP.Width;
23 int lnNewWidth = Width;
24 int lnNewHeight = Convert.ToInt32(loBMP.Height * lnRatio);
25
26 Bitmap bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
27 Graphics g = Graphics.FromImage(bmpOut);
28 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
29 g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
30 g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);
31
32 //Dispose old BMP object
33 loBMP.Dispose();
34
35 bmpOut.Save(FilePath);
36 bmpOut.Dispose();
37 }
The code is pretty obvious – save the file to the specified path, resize the image, dispose the old image and finally save the new image.
Happy Programming!