Last updated: 26th September 2024
In the summer of 2014, I have launched an online Image Resizer tool here in my website, which now processes an estimated 2500+ images every day. I am still working on the tool, improving it for better user experience. I am sharing a piece of code from the tool in this article explaining how to Resize an Image online using Asp.Net, without destroying or losing the Quality of the image.The example is for C# and Vb developers, especially beginners, who wish to learn the basics of image optimization, using Asp.Net.
Why it is important to resize an Image?
Images play a very important role in making presentations on a website. It engage visitors and help users to understand the content better.
However, images must be optimised for better performance. Large images takes time to load and uses more bandwidth, which can result in bad experience. Therefore, it is important to resize images by reducing the file size, without losing quality.
There are benefits of using small images on the web. You can easily share the images like emailing the images or share it on social media platforms.
Lets get on with the example.
<!DOCTYPE html> <html> <head> <title>Resize Image using Asp.Net</title> </head> <body> <form id="form1" runat="server"> <div> <asp:FileUpload ID="UploadFile" multiple="false" runat="server" BorderStyle="None" /> <input type="button" value="Upload Image" id="button" onserverclick="Resize" runat="server" /> <div id="Info" runat="server" style="padding:20px 0;"></div> </div> </form> </body> </html>
using System; using System.Web; using System.IO; using System.Drawing; public partial class _Default : System.Web.UI.Page { protected void Resize(object sender, EventArgs e) { // GET THE UPLOADED FILE. HttpFileCollection hfc = Request.Files; if (hfc.Count > 0) { HttpPostedFile hpf = hfc[0]; if (hpf.ContentLength > 0) { string sImageName = hpf.FileName; // first, save the file on the server. hpf.SaveAs(Server.MapPath("~/" + Path.GetFileName(sImageName))); // get original width and height of the image. Bitmap bitmap = new Bitmap(Server.MapPath("~/" + Path.GetFileName(hpf.FileName))); int iwidth = bitmap.Width; int iheight = bitmap.Height; bitmap.Dispose(); // release all resources using by the image. // SHOW DETAILS OF ORIGINAL IMAGE WITH SIZE. Info.InnerHtml = "<b>Original Image</b> "; Info.InnerHtml = Info.InnerHtml + "<br /> Width: " + iwidth + ", Height: " + iheight + "<br /> " + hpf.ContentLength / 1024 + " KB <br>"; // ONCE WE GOT ALL THE INFORMATION, WE'll NOW PROCESS IT. // CREATE AN IMAGE OBJECT USING ORIGINAL WIDTH AND HEIGHT. // ALSO DEFINE A PIXEL FORMAT (FOR RICH RGB COLOR). System.Drawing.Image objOptImage = new _ System.Drawing.Bitmap(iwidth, iheight, System.Drawing.Imaging. PixelFormat.Format16bppRgb555); // GET THE ORIGINAL IMAGE. using (System.Drawing.Image objImg = _ System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("~/" + sImageName))) { // RE-DRAW THE IMAGE USING THE NEWLY OBTAINED PIXEL FORMAT. using (System.Drawing.Graphics oGraphic = System.Drawing.Graphics.FromImage(objOptImage)) { var _1 = oGraphic; System.Drawing.Rectangle oRectangle = new System.Drawing.Rectangle(0, 0, iwidth, iheight); _1.DrawImage(objImg, oRectangle); } // SAVE THE OPTIMIZED IMAGE. objOptImage.Save(HttpContext.Current.Server.MapPath("~/images/" + sImageName), _ System.Drawing.Imaging.ImageFormat.Jpeg); objImg.Dispose(); } objOptImage.Dispose(); // FINALLY SHOW THE OPTIMIZED IMAGE DETAILS WITH SIZE. Bitmap bitmap_Opt = new Bitmap(Server.MapPath("~/images/" + Path.GetFileName(sImageName))); int iwidth_Opt = bitmap_Opt.Width; int iheight_Opt = bitmap_Opt.Height; bitmap_Opt.Dispose(); // FOR SIZE. FileInfo OptImgInfo = new FileInfo(Server.MapPath("~/images/" + Path.GetFileName(sImageName))); long lFileSize = OptImgInfo.Length; // GET THE SIZE IN BYTES. Info.InnerHtml = Info.InnerHtml + "<br / ><b>Optimized Image</b>"; Info.InnerHtml = Info.InnerHtml + "<br /> Width: " + iwidth_Opt + ", Height: " + iheight_Opt; Info.InnerHtml = Info.InnerHtml + "<br /><span style=color:green>" + lFileSize / 1024 + " KB</span>"; } } } }
Output
The above image clearly shows how the tool has reduced the size of an image from its original 5724 KB to 311 KB.
I chose a .jpg image for the above demo. You can choose other formats like png, bmp etc.
Option Explicit On Imports System.IO Imports System.Drawing Partial Class _Default Inherits System.Web.UI.Page Protected Sub Resize(ByVal sender As Object, ByVal e As EventArgs) ' GET THE UPLOADED FILE. Dim hfc As HttpFileCollection = Request.Files If hfc.Count > 0 Then Dim hpf As HttpPostedFile = hfc(0) If hpf.ContentLength > 0 Then Dim sImageName As String = hpf.FileName ' FIRST SAVE THE FILE ON THE SERVER. hpf.SaveAs(Server.MapPath("~/" & Path.GetFileName(sImageName))) ' ORIGINAL WIDTH AND HEIGHT. Dim bitmap As New Bitmap(Server.MapPath("~/" & Path.GetFileName(hpf.FileName))) Dim iwidth As Integer = bitmap.Width Dim iheight As Integer = bitmap.Height bitmap.Dispose() ' SHOW DETAILS OF ORIGINAL IMAGE WITH SIZE. Info.InnerHtml = "<b>Original Image</b> " Info.InnerHtml = Info.InnerHtml & "<br /> Width: " & iwidth & ", Height: " & iheight & "<br /> " & _ Double.Parse(hpf.ContentLength / 1024).ToString("N0") & " KB <br>" ' ONCE WE GOT ALL THE INFORMATION, WE'll NOW PROCESS IT. ' CREATE AN IMAGE OBJECT USING ORIGINAL WIDTH AND HEIGHT. ' ALSO DEFINE A PIXEL FORMAT (FOR RICH RGB COLOR). Dim objOptImage As System.Drawing.Image = _ New System.Drawing.Bitmap(iwidth, iheight, _ System.Drawing.Imaging.PixelFormat.Format16bppRgb555) ' GET THE ORIGINAL IMAGE. Using objImg As System.Drawing.Image = _ System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("~/" & sImageName)) ' RE-DRAW THE IMAGE USING THE NEWLY OBTAINED PIXEL FORMAT. Using oGraphic As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(objOptImage) With oGraphic Dim oRectangle As New System.Drawing.Rectangle(0, 0, iwidth, iheight) .DrawImage(objImg, oRectangle) End With End Using ' SAVE THE OPTIMIZED IMAGE. objOptImage.Save(HttpContext.Current.Server.MapPath("~/images/" & sImageName), _ System.Drawing.Imaging.ImageFormat.Jpeg) objImg.Dispose() End Using objOptImage.Dispose() ' FINALLY SHOW THE OPTIMIZED IMAGE DETAILS WITH SIZE. Dim bitmap_Opt As New Bitmap(Server.MapPath("~/images/" & Path.GetFileName(sImageName))) Dim iwidth_Opt As Integer = bitmap_Opt.Width Dim iheight_Opt As Integer = bitmap_Opt.Height bitmap_Opt.Dispose() ' FOR SIZE. Dim OptImgInfo As New FileInfo(Server.MapPath("~/images/" & Path.GetFileName(sImageName))) Dim ifileSize As Integer = OptImgInfo.Length ' GET THE SIZE IN BYTES. Info.InnerHtml = Info.InnerHtml & "<br / ><b>Optimized Image</b>" Info.InnerHtml = Info.InnerHtml & "<br /> Width: " & iwidth_Opt & ", Height: " & iheight_Opt Info.InnerHtml = Info.InnerHtml & "<br /><span style=color:green>" & _ Double.Parse(ifileSize / 1024).ToString("N0") & " KB</span>" End If End If End Sub End Class
Shrink the Image by 50%
Now, Let's reduce the width and height of the image by 50% and check the quality and size of the image. To do this, simply divide the iwidth and iheight variables by 2.
int iwidth = bitmap.Width; int iheight = bitmap.Height; bitmap.Dispose(); Info.InnerHtml = "<b>Original Image</b> "; Info.InnerHtml = Info.InnerHtml + "<br /> Width: " + iwidth + ", Height: " + iheight + "<br /> " + hpf.ContentLength / 1024 + " KB <br>"; // REDUCE 50%. iwidth = iwidth / 2; iheight = iheight / 2;
Place the highlighted code right after showing the Original Image info.
bitmap.Dispose() Info.InnerHtml = "<b>Original Image</b> " Info.InnerHtml = Info.InnerHtml & "<br /> Width: " & iwidth & _ ", Height: " & iheight & "<br /> " & _ Double.Parse(hpf.ContentLength / 1024).ToString("N0") & " KB <br>" ' REDUCE 50%. iwidth = iwidth / 2 iheight = iheight / 2
Note: The results may wary depending upon the image format.