Create Fixed Size Cropper Using ASP.Net and jQuery

Introduction

 
This article explains how to create a Fixed Size Cropper using ASP.NET and jQuery.
 
On many websites, we can crop our image and then can paste it on a timeline. They often provide a fixed-sized cropper to crop our image. This article will help you to create the same type of cropper that can be used on your website.
 
Step 1
 
First of all, add a new Web Application to your Visual Studio and name it "Crop Image".
 
crop1.jpg
 
Now you need to add three jQuery files to the application; they are:
  1. jquey.min.js
  2. jquery.jcrop.min.js
  3. jquery.jcrop.js
You can download these files from the Zip File provided above.
 
Step 2
 
Now we need to add a few Panels, Hidden Fields, a Button, a Label and so on to our application as in the following:
  1. <div>  
  2.     <asp:Panel ID="pnlUpload" runat="server">  
  3.         <asp:FileUpload ID="Upload" runat="server" />  
  4.         <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload" />  
  5.         <asp:Label ID="lblError" runat="server" Visible="false" />  
  6.     </asp:Panel>  
  7.     <asp:Panel ID="pnlCrop" runat="server" Visible="false">  
  8.         <asp:Image ID="imgCrop" runat="server" />  
  9.         <asp:HiddenField ID="X" runat="server" />  
  10.         <asp:HiddenField ID="Y" runat="server" />  
  11.         <asp:HiddenField ID="W" runat="server" />  
  12.         <asp:HiddenField ID="H" runat="server" />  
  13.     </asp:Panel>  
  14.     <asp:Panel ID="pnlCropped" runat="server" Visible="false">  
  15.         <asp:Image ID="imgCropped" runat="server" />  
  16.     </asp:Panel>  
  17.     <asp:Button ID="btnCrop" runat="server" Text="Crop" OnClick="btnCrop_Click" />  
  18. </div> 
Now go to the head section of the application and add the following code there:
  1. <script>  
  2. $(window).load(function() {  
  3.     var jcrop_api;  
  4.     var i, ac;  
  5.   
  6.     initJcrop();  
  7.   
  8.     function initJcrop() {  
  9.         jcrop_api = $.Jcrop('#imgCrop', {  
  10.             onSelect: storeCoords,  
  11.             onChange: storeCoords  
  12.         });  
  13.         jcrop_api.setOptions({ aspectRatio: 1 / 1 });  
  14.         jcrop_api.setOptions({  
  15.             minSize: [250, 250],  
  16.             maxSize: [250, 350]  
  17.         });  
  18.         jcrop_api.setSelect([140, 180, 160, 180]);  
  19.     };  
  20.   
  21.     function storeCoords(c) {  
  22.         jQuery('#X').val(c.x);  
  23.         jQuery('#Y').val(c.y);  
  24.         jQuery('#W').val(c.w);  
  25.         jQuery('#H').val(c.h);  
  26.     };  
  27. });  
  28. </script> 
This code will help to make the cropper a fixed size whose start and end coordinates can also be set from here.
 
Step 3
 
Now we will move to the aspx.cs file and will do the coding there.
 
First, we will add code to the Upload Button that will upload the image from our computer.
  1. Boolean FileOK = false;  
  2. Boolean FileSaved = false;  
  3.   
  4. if (Upload.HasFile) {  
  5.     Session["UploadImage"] = Upload.FileName;  
  6.     String ExtensionofImage = Path.GetExtension(Session["UploadImage"].ToString()).ToLower();  
  7.     String[] allowed = { ".png"".jpeg"".jpg"".gif" };  
  8.     for (int i = 0; i < allowed.Length; i++) {  
  9.         if (ExtensionofImage == allowed[i]) {  
  10.             FileOK = true;  
  11.         }  
  12.     }  
  13. }  
  14. if (FileOK) {  
  15.     try {  
  16.         Upload.PostedFile.SaveAs(path + Session["UploadImage"]);  
  17.         FileSaved = true;  
  18.     } catch (Exception ex) {  
  19.         lblError.Text = "Sorry Can't Upload" + ex.Message.ToString();  
  20.         lblError.Visible = true;  
  21.         FileSaved = false;  
  22.     }  
  23. else {  
  24.     lblError.Text = "Select some Other Image";  
  25.     lblError.Visible = true;  
  26. }  
  27.   
  28. if (FileSaved) {  
  29.     pnlUpload.Visible = false;  
  30.     pnlCrop.Visible = true;  
  31.     imgCrop.ImageUrl = "images/" + Session["UploadImage"].ToString();  

This code will check the extension of the file if the extension is .png or .jpeg, or .jpg or .gif then if any file has an extension other than these extensions then the file will not be uploaded and it will throw an exception.
 
Step 4
 
Now we will do the code for the Crop Button.
  1. string Img = Session["UploadImage"].ToString();  
  2. int w = Convert.ToInt32(W.Value);  
  3. int h = Convert.ToInt32(H.Value);  
  4. int x = Convert.ToInt32(X.Value);  
  5. int y = Convert.ToInt32(Y.Value);  
  6. byte[] CropImage = Cut(path + Img, w, h, x, y);  
  7. using (MemoryStream mem = new MemoryStream(CropImage, 0, CropImage.Length))  
  8. {  
  9.     mem.Write(CropImage, 0, CropImage.Length);  
  10.     using (SD.Image CroppedImage = SD.Image.FromStream(mem, true))  
  11.     {  
  12.         string SaveTo = path + "crop" + Img;  
  13.         CroppedImage.Save(SaveTo, CroppedImage.RawFormat);  
  14.         pnlCrop.Visible = false;  
  15.         pnlCropped.Visible = true;  
  16.         imgCropped.ImageUrl = "images/crop" + Img;  
  17.     }  

This code will convert the coordinates into integers and then crop the image depending on these values.
  1. static byte[] Cut(string Img, int Breadth, int Length, int X, int Y)  
  2. {  
  3.     try  
  4.     {  
  5.         using (SD.Image OriginalImage = SD.Image.FromFile(Img))  
  6.         {  
  7.             using (SD.Bitmap bmp = new SD.Bitmap(Breadth, Length))  
  8.             {  
  9.                 bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution);  
  10.                 using (SD.Graphics Graphic = SD.Graphics.FromImage(bmp))  
  11.                 {  
  12.                     Graphic.SmoothingMode = SmoothingMode.AntiAlias;  
  13.                     Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;  
  14.                     Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;  
  15.                     Graphic.DrawImage(OriginalImage, new SD.Rectangle(0, 0, Breadth, Length), X, Y, Breadth, Length, SD.GraphicsUnit.Pixel);  
  16.                     MemoryStream ms = new MemoryStream();  
  17.                     bmp.Save(ms, OriginalImage.RawFormat);  
  18.                     return ms.GetBuffer();  
  19.                 }  
  20.             }  
  21.         }  
  22.     }  
  23.     catch (Exception Ex)  
  24.     {  
  25.         throw (Ex);  
  26.     }  

This code will be added just after the Crop Button's code.
 
Output
 
First, this page will appear.
 
crop2.jpg
 
Now you need to choose a file and then click on the "Upload" button.
 
This will get the image to be cropped.
 
crop3.jpg
 
Now adjust the cropper and click on the Crop Button to crop it.
 
crop4.jpg


Recommended Free Ebook
Similar Articles