Friday, June 22, 2012

Crop Image in ASP.NET using JCrop, JQuery

You might have seen various websites and web application giving features to Crop your image and save it. That can be done in DHTML or in Javascript. Lets see one example of doing it with the help of JCrop which can be download from here (JCrop)



How to start

1. First include the following file into your project

  • jquery.Jcrop.js
  • jquery.Jcrop.min.js
  • jquery.min.js
or you can directly drag and drop the JCrop folder in your project

2. We need to write code in our page. Include the JQuery function in the page and also add one event for crop control for updation of the cordinates in the variable on selection by users. Check the head section of the page given below

                    <head runat="server">
                        <title></title>
                        <script src="js/jquery.min.js"></script>
                        <script src="js/jquery.Jcrop.min.js"></script>
                        <link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
                        <script language="Javascript">
                            jQuery(document).ready(function () {  
                                 // Create variables (in this scope) to hold the API and image size
        var jcrop_api, boundx, boundy;                              
                                $('#cropbox').Jcrop({
                                    onChange: updatePreview,
                                    onSelect: updatePreview,
                                    aspectRatio: 1,
                                    boxWidth: 450,
                                    boxHeight: 400,
                                    maxSize: [300, 300],
                                    minSize: [200, 200]
                                }, function () {
                                    // Use the API to get the real image size
                                    var width = $('#cropbox').width();
                                    var height = $('#cropbox').height();
                                    var rect = new Array();
                                    rect[0] = 1;
                                    rect[1] = 1;
                                    rect[2] = width - 1;
                                    rect[3] = height - 1;
                                    if (width >= 300) {
                                        rect[0] = width / 6;
                                        rect[2] = width - 100;
                                    }
                                    if (height >= 300) {
                                        rect[1] = 10;
                                        rect[3] = height - (height / 4);
                                    }
                                    var bounds = this.getBounds();
                                    boundx = bounds[0];
                                    boundy = bounds[1];
                                    // Store the API in the jcrop_api variable
                                    jcrop_api = this;
                                    jcrop_api.setSelect(rect);
                                });
                            });

                            function updatePreview(c) {
                                jQuery('#X').val(c.x);
                                jQuery('#Y').val(c.y);
                                jQuery('#W').val(c.w);
                                jQuery('#H').val(c.h);

                                if (parseInt(c.w) > 0) {
                                    var rx = 100 / c.w;
                                    var ry = 100 / c.h;

                                    $('#preview').css({
                                        width: Math.round(rx * boundx) + 'px',
                                        height: Math.round(ry * boundy) + 'px',
                                        marginLeft: '-' + Math.round(rx * c.x) + 'px',
                                        marginTop: '-' + Math.round(ry * c.y) + 'px'
                                    });
                                }
                            };                          
                        </script>
                    </head>
                

3. In your body section add following form to your page

                   
  <div>
<asp:button id="Submit" runat="server" text="Crop Image" onclick="Submit_Click" />
 
<asp:image id="cropedImage" runat="server" visible="False" />
 
<table>
<tr>
    <td>
        <div>
            <img src="Sunset.jpg" id="cropbox" />
        </div>
    </td>
    <td valign="middle">
        <div>
            <table>
                <tr>
                    <td class="headInnerLarger">
                        Thumbnail Preview:
                    </td>
                </tr>
                <tr>
                    <td>
                        <div style="width: 100px; height: 100px; overflow: hidden;">
                            <img src="Sunset.jpg" id="preview" />
                        </div>
                    </td>
                </tr>
            </table>
        </div>
    </td>
</tr>
</table>
<asp:hiddenfield id="X" runat="server" />
<asp:hiddenfield id="Y" runat="server" />
<asp:hiddenfield id="W" runat="server" />
<asp:hiddenfield id="H" runat="server" />
</div>
                

4. We need to handle the click event of crop button in our code and crop the image there

                
protected void Submit_Click(object sender, EventArgs e)
{
  if (this.IsPostBack)
  {
   //Get the Cordinates                
   int x = Convert.ToInt32(X.Value);
   int y = Convert.ToInt32(Y.Value);
   int w = Convert.ToInt32(W.Value);
   int h = Convert.ToInt32(H.Value);

   //Load the Image from the location
   System.Drawing.Image image = Bitmap.FromFile(
         HttpContext.Current.Request.PhysicalApplicationPath + "Sunset.jpg");
  
  //Create a new image from the specified location to                
  //specified height and width                
  Bitmap bmp = new Bitmap(w, h, image.PixelFormat);
  Graphics g = Graphics.FromImage(bmp);
  g.DrawImage(image, new Rectangle(0, 0, w, h), new Rectangle(x, y, w, h), 
                     GraphicsUnit.Pixel);

  //Save the file and reload to the control
  bmp.Save(HttpContext.Current.Request.PhysicalApplicationPath + "Sunset2.jpg",          image.RawFormat);
  cropedImage.Visible = true;
  cropedImage.ImageUrl = ".\\Sunset2.jpg";
 }
}
             

1 comment: