How to Resize an Image in Asp.Net Without Destroying Quality C# and Vb.Net

← PrevNext →

In the summer of 2014, I have launched an online Image Resizer tool on my blog, which now serves an estimated 450+ images every day. I am still working on improving the tool 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 article and its example is for C# and Vb.Net developers, especially beginners, who wish to learn the basics of image optimization, using tools provided in Asp.Net.

Crop an Image

See this demo

Why it is important to resize an Image?

There are many reasons why users often look for an online tool for resizing images. Images play a very important role in making presentations on the web, in particular. We crop the image to slice out the part we like, we format, optimize and shrink the images, so we can easily email it or display it on a social site. Large images can take lot of time to upload and share on the web.

You must read: How to resize multiple images on your browser without losing the quality of the images

These tools are useful in making logos, optimize digital images, advertising banners, family pictures or corporate images. Therefore, its always a challenge for web developers to optimize the images without destroying the quality.

So, let us do it.

The Markup
<!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>
Code Behind (C#)
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)));

                // ORIGINAL WIDTH AND HEIGHT.
                Bitmap bitmap = new Bitmap(Server.MapPath("~/" + Path.GetFileName(hpf.FileName)));

                int iwidth = bitmap.Width;
                int iheight = 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 /> " + 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.Png);

                    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>";
            }
        }
    }
}
Vb.Net
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.Png)

                    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

Output

Re-size Image using Asp.Net

Wow, this is great. The above image clearly shows how the tool has reduced the size of an image from its original 969 KB to 399 KB. This is interesting. I chose a .png file for the demo; you can choose any type of file to test the result. It works fine with .jpg and .bmp also.

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.

C#
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.

Vb.Net
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

Again, without affecting the quality of the image, the program quickly made the image 50% smaller than the original, also reduced the size.

Original Image
Width: 1188, Height: 517
969 KB

Optimized Image
Width: 594, Height: 258
106 KB

Note: The above output may show a different result depending upon the image you have chosen.

See this demo

Also Read: FileReader API - Resize an Image on your Computer with FileReader and HTML5 Canvas without Losing Image Quality

Conclusion

Weather it is due to space crunch or displaying images on the web without effecting user experience, web developers always face a challenge in optimizing images without destroying or losing the quality of images. It is always useful to keep these tools handy so you can quickly and efficiently resize images from anywhere without any fuss.

Thanks for reading. 🙂

← PreviousNext →