Tuesday, 13 January 2015

Upload and Resizing Image in C# (Without Losing Quality )

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
   
    <script src="../Include/JS/2.1JS.js"></script>

    <link href="../Include/CSS/bootstrap.css" rel="stylesheet" />


<script type="text/javascript">

    $(document).ready(function () {

        $("#BtnUpload").click(function (event) {

            var uploadfiles = $("#MultipleFilesUpload").get(0);

            var uploadedfiles = uploadfiles.files;

            var fromdata = new FormData();

           for (var i = 0; i < uploadedfiles.length; i++) {

        
            fromdata.append(uploadedfiles[i].name, uploadedfiles[i]);

           }
        //   alert(fromdata);
            var choice = {};

            choice.url = "../Handler/hlrMultiImg.ashx";

            choice.type = "POST";

            choice.data = fromdata;

            choice.contentType = false;

            choice.processData = false;

            choice.success = function (result) {
               alert(result);
              //  document.getElementById("ok").src = result;
               // alert(result);
            };

            choice.error = function (err) { alert(err.statusText); };

            $.ajax(choice);

            event.preventDefault();

        });

    });

</script>
</head>
<body>
   

<form id="form1" runat="server">

    <h2>ASP.NET</h2>

    <p class="lead">Selcting Multiple Files using jQuery and Generic Handler</p>  



    <div class="form-group">

        <div>
            <img id="ok"/>
            <asp:Label ID="Label1" runat="server" AssociatedControlID="MultipleFilesUpload">Select Files</asp:Label>           

            <asp:FileUpload ID="MultipleFilesUpload" runat="server" AllowMultiple="true" />          

        </div>

    </div>

    <div class="form-group">

        <div class="col-md-offset-2 col-md-10">

            <asp:Button runat="server" ID="BtnUpload" Text="Upload Files" CssClass="btn btn-default" />

        </div>

    </div>  

 </form>
</body>
</html>










IN HANDLER ashx file





using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing.Drawing2D;
public class hlrMultiImg : IHttpHandler
{



    public void ProcessRequest(HttpContext context)
    {

        if (context.Request.Files.Count > 0)
        {

            HttpFileCollection SelectedFiles = context.Request.Files;

            for (int i = 0; i < SelectedFiles.Count; i++)
            {

                HttpPostedFile PostedFile = SelectedFiles[i];
                string FileName = context.Server.MapPath("~/CartidgeImage/" + PostedFile.FileName);
                //   PostedFile.SaveAs(FileName);

                string filename = Path.GetFileName(PostedFile.FileName);
                string targetPath = context.Server.MapPath("~/CartidgeImage/" + filename);
                Stream strm = PostedFile.InputStream;
                var targetFile = targetPath;
                //Based on scalefactor image size will vary
                GenerateThumbnails(0.5, strm, targetFile);
                //   BindDataList();

                //   context.Response.Write("../CartidgeImage/"+PostedFile.FileName);

            }

        }



        else
        {

            context.Response.ContentType = "text/plain";

            context.Response.Write("Please Select Files");

        }



        context.Response.ContentType = "text/plain";

        // context.Response.Write(FileName);

    }



    public bool IsReusable
    {

        get
        {

            return false;

        }

    }




    private void GenerateThumbnails(double scaleFactor, Stream sourcePath, string targetPath)
    {
        using (var image = Image.FromStream(sourcePath))
        {
            var newWidth = (int)(image.Width * scaleFactor);
            var newHeight = (int)(image.Height * scaleFactor);
            var thumbnailImg = new Bitmap(newWidth, newHeight);
            var thumbGraph = Graphics.FromImage(thumbnailImg);
            thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
            thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
            thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
            var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
            thumbGraph.DrawImage(image, imageRectangle);
            thumbnailImg.Save(targetPath, image.RawFormat);
        }
    }
}

No comments:

Post a Comment