How To Compress Large Size Image Without Losing Image Quality Using ASP.NET

SQL Database

  • Create Database Sample
  • Create Table

You can create a table using the following query -  

create table tblImageInfo(id int identity(1,1) primary key,Name nvarchar(30),Content nvarchar(200));
 
Now, let's go ahead and start the process of compressing the images.

Step 1 - Open Visual Studio -> select New Project -> select Empty ASP.NET Web application

Step 2 - Create a folder named Images. 

Step 3 - Here is the code for Default.aspx page.

output
  1. <body>  
  2.     <form id="form1" runat="server">  
  3.     <div align="center">  
  4.         <br />  
  5.         Name:<asp:TextBox ID="txtname" runat="server"></asp:TextBox>  
  6.         <br />  
  7.         <br />  
  8.         
  9.     UploadImage :<asp:FileUpload ID="fileupload1" runat="server" />  
  10.         <br />  
  11.         <br />  
  12. <asp:Button ID="btnupload" runat="server" Text="Upload" OnClick="btnupload_Click"  />  
  13.          <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false"  
  14.        Font-Names = "Arial" >  
  15.     <Columns>  
  16.        <asp:BoundField DataField = "id" HeaderText = "ID" Visible="false" />  
  17.        <asp:BoundField DataField = "Name" HeaderText = "Image Name" />  
  18.        <asp:TemplateField>  
  19.            <ItemTemplate>  
  20.                <img src="<%#Eval("Content")%>" alt="<%#Eval("Name")%>" width="125px" height="150px"/>  
  21.            </ItemTemplate>  
  22.        </asp:TemplateField>  
  23.     </Columns>  
  24.     </asp:GridView>  
  25.   
  26.           
  27.     </div>  
  28.     </form>  
  29. </body>  
Step 4 - This is the code for default.aspx.cs file.
  1. public partial class Default : System.Web.UI.Page  
  2.   {  
  3.       SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);  
  4.       protected void Page_Load(object sender, EventArgs e)  
  5.       {  
  6.           if (!IsPostBack)  
  7.           {  
  8.               BindGridView();  
  9.           }  
  10.       }  
  11.   
  12.       protected void btnupload_Click(object sender, EventArgs e)  
  13.       {  
  14.           string filename = Path.GetFileName(fileupload1.PostedFile.FileName);  
  15.           string storedb = "Images/" + filename + "";  
  16.           string targetPath = Server.MapPath("Images/" + filename);  
  17.           Stream strm = fileupload1.PostedFile.InputStream;  
  18.           var targetFile = targetPath;  
  19.             
  20.           ReduceImageSize(0.5, strm, targetFile);  
  21.           //insert reduced size image in db  
  22.           con.Open();  
  23.           SqlCommand cmd = new SqlCommand("Insert into tblImageInfo(Name,Content)values('"+txtname.Text+"','"+storedb+"')", con);  
  24.           cmd.ExecuteNonQuery();  
  25.   
  26.       }  
  27.   
  28.       protected void BindGridView()  
  29.       {  
  30.           DataTable dt = new DataTable();             
  31.           string strQuery = "select * from tblImageInfo order by id desc";  
  32.           SqlCommand cmd = new SqlCommand(strQuery);              
  33.           SqlDataAdapter da = new SqlDataAdapter();  
  34.           cmd.CommandType = CommandType.Text;  
  35.           cmd.Connection = con;  
  36.           try  
  37.           {  
  38.               con.Open();  
  39.               da.SelectCommand = cmd;  
  40.               da.Fill(dt);  
  41.               GridView1.DataSource = dt;  
  42.               GridView1.DataBind();  
  43.           }  
  44.           catch (Exception ex)  
  45.           {  
  46.               Response.Write(ex.Message);  
  47.           }  
  48.           finally  
  49.           {  
  50.               con.Close();  
  51.               da.Dispose();  
  52.               con.Dispose();  
  53.           }  
  54.   
  55.       }  
  56.       private void ReduceImageSize(double scaleFactor, Stream sourcePath, string targetPath)  
  57.       {  
  58.           using (var image = System.Drawing.Image.FromStream(sourcePath))  
  59.           {  
  60.               var newWidth = (int)(image.Width * scaleFactor);  
  61.               var newHeight = (int)(image.Height * scaleFactor);  
  62.               var thumbnailImg = new Bitmap(newWidth, newHeight);  
  63.               var thumbGraph = Graphics.FromImage(thumbnailImg);  
  64.               thumbGraph.CompositingQuality = CompositingQuality.HighQuality;  
  65.               thumbGraph.SmoothingMode = SmoothingMode.HighQuality;  
  66.               thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;  
  67.               var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);  
  68.               thumbGraph.DrawImage(image, imageRectangle);  
  69.               thumbnailImg.Save(targetPath, image.RawFormat);  
  70.           }  
  71.       }  
  72.   }  
Step 5 - Build and run the application. Upload uncompressed images and get the compressed ones. You can check the image size.
application
Ebook Download
View all
Learn
View all