How to image compression in asp.net with c#


In This Article, We Learn  Compress Large Size Image Without Losing Image Quality Using ASP.NET

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

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="jobnow_Default" %>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" 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>

















Source Code C#:-


  1. 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);
        }
    }


Demo:- Compressed image without losing the quality but now image size 512KB
















Note: -  In this article, you will learn how to resize and compress an image

Post a Comment

0 Comments