Showing posts with label Compress Jpeg. Show all posts
Showing posts with label Compress Jpeg. Show all posts

Tuesday, 26 November 2013

How to Compress JPEG File in Asp.Net

How to Compress JPEG File in Asp.Net:-

Through this code jpeg files will be compressed without loosing the resolution. 

First you need to create 2 folders in your project.
1. UploadImages
2. CompressedImages



Code For aspx page:-


<div>
<h3>Upload File To Compress</h3>
<asp:FileUpload ID="fu_Compress" runat="server" Style="background-color: #83CF32;
border-radius: 5px; -moz-border-radius: 5px; height: 30px; color: White; -webkit-border-radius: 5px;" />
<asp:RequiredFieldValidator ID="RFVfileupload" runat="server" ToolTip="Image required."
CssClass="failureNotification" Display="Dynamic" SetFocusOnError="true" ErrorMessage="Image required." ControlToValidate="fu_Compress" ValidationGroup="sbmitbtn" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
(Max size limit 5MB per file)
<asp:Label Font-Bold="true" ID="lblmsz" runat="server"></asp:Label></p>
<asp:Button ID="btnsave" runat="server" Text="Compress" Style="background-color: #83CF32;
border-radius: 5px; -moz-border-radius: 5px; height: 30px; color: White; -webkit-border-radius: 5px;"
CssClass="Button" OnClick="btnsave_Click" ValidationGroup="sbmitbtn" />
</div>

Code For aspx.cs page:-


Name Spaces:-


using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Drawing;
using System.Web.Security;
using System.IO;
using System.IO.Compression;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Net;


Code:-


  private string ActualPath
{
            get { return (ViewState["ActualPath"] == null ? string.Empty : ViewState["ActualPath"].ToString()); }
            set { ViewState["ActualPath"] = value; }
        }

private string ImagePhotoPath
{
get { return (ViewState["Path"] == null ? string.Empty : ViewState["Path"].ToString()); }
set { ViewState["Path"] = value; }
}


Method for Compressing JPEG File:-


 private void CompressJpeg(double scaleFactor, Stream sourcePath, string targetPath, int width, int height, string fileName)
        {
            try
            {
                using (var image = Image.FromStream(sourcePath))
                {
                    var compImg = new Bitmap(width, height);
                    var newGraph = Graphics.FromImage(compImg);
                    newGraph.CompositingQuality = CompositingQuality.HighQuality;
                    newGraph.SmoothingMode = SmoothingMode.HighQuality;
                    newGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    var imageRectangle = new Rectangle(0, 0, width, height);
                    newGraph.DrawImage(image, imageRectangle);
                    compImg.Save(targetPath, image.RawFormat);
                    lblmsz.Text = "File Compressed Succesfully.";
                    lblmsz.ForeColor = Color.Green;
                   }
            }
            catch (Exception e)
            {
                lblmsz.Text = e.Message.ToString();
                lblmsz.ForeColor = Color.Red;
             }
        }



Code for Save Button:-


protected void btnsave_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
           HttpFileCollection fileCollection = Request.Files;
                string notuploaded = string.Empty;
                string fileName = Path.GetFileName(fu_Compress.FileName);

                if (fu_Compress.PostedFile.ContentLength < 5242880)
                {

                    string ext4 = Path.GetExtension(fu_Compress.FileName).ToUpper();
                    string AllowedImageTypes = System.Configuration.ConfigurationManager.AppSettings["AllowedImageTypes"].ToString();
                    if (AllowedImageTypes.Contains(ext4))
                    {
                        string RelativePath = fu_Compress.FileName;
                        ActualPath = fu_Compress.FileName;
                        fu_Compress.SaveAs(Server.MapPath("~/UploadImages/" + fileName));
                        System.Drawing.Image objImage = System.Drawing.Image.FromFile(Server.MapPath("~/UploadImages/" + fileName));
                        int imgwid = objImage.Width;
                        int imghig = objImage.Height;
                        string targetPath = Server.MapPath("~/CompressedImages/" + fileName);
                        Stream strm = fu_Compress.PostedFile.InputStream;
                        var targetFile = targetPath;
                        CompressJpeg(0.5, strm, targetFile, imgwid, imghig, fileName);//Code use for without lossing image quality.

                        DateTime goodDateHolder = Convert.ToDateTime(DateTime.Now.ToShortDateString());

                    }
                    else
                    {
                        lblmsz.Text = "Only JPEG Files";
                        lblmsz.ForeColor = Color.Red;
                    }
                }
                else
                {
                    lblmsz.Text = "Max File Limit 5MB";
                    lblmsz.ForeColor = Color.Red;
                }

            }
        }







Don't forget to leave your feedback and comments below..!