Image compression without losing quality in asp.net c#

In this article, we learn how to compress large size images without losing image quality and without losing image size.


We have taken an image i.e. size 3.12MB and how we will see how to compress that image without losing the image quality and size.



Source code:

<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" />
        <asp:Button ID="btnsave" runat="server" OnClick="btnsave_Click" Text="Button" />
   
    </div>
    </form>
</body>

</html>

Code Behind(c#):

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class imagecompressor : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    private void compressimagesize(double scaleFactor, Stream sourcePath, string targetPath)
    {
        using (var image = System.Drawing.Image.FromStream(sourcePath))
        {
            var imgnewwidth = (int)(image.Width * scaleFactor);
            var imgnewheight = (int)(image.Height * scaleFactor);
            var imgthumnail = new Bitmap(imgnewwidth, imgnewheight);
            var imgthumbgraph = Graphics.FromImage(imgthumnail);
            imgthumbgraph.CompositingQuality = CompositingQuality.HighQuality;
            imgthumbgraph.SmoothingMode = SmoothingMode.HighQuality;
            imgthumbgraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
            var imageRectangle = new Rectangle(0, 0, imgnewwidth, imgnewheight);
            imgthumbgraph.DrawImage(image, imageRectangle);
            imgthumnail.Save(targetPath, image.RawFormat);
        }
    }


   
    protected void btnsave_Click(object sender, EventArgs e)
    {
        string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
        string targetPath = Server.MapPath("Images/" + filename);
        string saveimage = "Images/" + filename + "";
        Stream strm = FileUpload1.PostedFile.InputStream;
        var
targetFile = targetPath;

        compressimagesize(0.5, strm, targetFile);
    }
}



Out-put:

Compressed image without losing the quality but now image size 712KB



Image compression without losing quality in asp.net c# Image compression without losing quality in asp.net c# Reviewed by NEERAJ SRIVASTAVA on 11:03:00 AM Rating: 5

No comments:

Powered by Blogger.