Thursday, November 22

Image cropping using jquery

Introduction:-
                     Here I have explained How to crop image with jquery  and asp.net.
Description:-
In this article I will explain how you can crop your selected image using jQuery and asp.net.
You have follow the below steps to get the result.It will be better if you will copy and paste the code I have written below to see the output.


·         First create one css style sheet,here I am providing as jcrop.css




jcrop.css


.jcrop-holder
{
       text-align: left;
}
.jcrop-vline, .jcrop-hline
{
       font-size: 0;
       position: absolute;
       background: white url('../images/Jcrop.gif') top left repeat;
}
.jcrop-vline { height: 100%; width: 1px !important; }
.jcrop-hline { width: 100%; height: 1px !important; }
.jcrop-handle {
       font-size: 1px;
       width: 7px !important;
       height: 7px !important;
       border: 1px #eee solid;
       background-color: #333;
       *width: 9px;
       *height: 9px;
}
.jcrop-tracker {
       *background-color: gray;
       width: 100%; height: 100%;
}
.custom .jcrop-vline,
.custom .jcrop-hline
{
       background: yellow;
}
.custom .jcrop-handle
{
       border-color: black;
       background-color: #C7BB00;
       -moz-border-radius: 3px;
       -webkit-border-radius: 3px;
}
.coor
{
    width:30px;
}

·         Second create one js file,here I am written function inside crop.js

crop.js


function Init() {
    $(function() {
    $('#MyoriginalImage').Jcrop({
            onChange: showCoords,
            onSelect: showCoords
        });
    });
    // supporting code for IE to force "overflow: auto;"
    document.getElementById("imgContainer").Mystylefolder["position"] = "relative";
}
function showCoords(MyC) {
    $('#Myx1').val(MyC.x);
    $('#Myy1').val(MyC.y);
    $('#Myx2').val(MyC.Myx2);
    $('#Myy2').val(MyC.Myy2);
    $('#w').val(MyC.w);
    $('#h').val(MyC.h);
};
function ValidateSelectedPortion() {
    if (document.getElementById("w").value == "" || document.getElementById("w").value == "0"
        || document.getElementById("h").value == "" || document.getElementById("h").value == "0") {
        alert("No area for crop was selected");
        return false;
    }
}

·         Third create second  js file,here write  function inside jcrop.js,you can name it in your choice or simple copy and paste this code.

jcrop.js
 (function($) {
$.Jcrop = function(Myobj,Myopt )
{
       var Myobj = Myobj, Myopt  = Myopt ;
       if (typeof(Myobj) !== 'object') Myobj = $(Myobj)[0];
       if (typeof(Myopt ) !== 'object') Myopt  = { };
       if (!('trackDocument' in Myopt ))
       {
              Myopt .trackDocument = $.browser.msie ? false : true;
              if ($.browser.msie &&$.browser.version.split('.')[0] == '8')
                     Myopt .trackDocument = true;
       }
       if (!('keySupport' in Myopt ))
                     Myopt .keySupport = $.browser.msie ? false : true;
             
       var defaults = {
              //providing some Basic Settings
              trackDocument:             false,
              baseClass:                 'jcrop',
              addClass:                  null,
              //Providing some Styling Options
              bgColor:                   'black',
              bgOpacity:                 .6,
              borderOpacity:             .4,
              handleOpacity:             .5,
              handlePad:                 5,
              handleSize:                9,
              handleOffset:        5,
              edgeMargin:                14,
              aspectRatio:         0,
              keySupport:                true,
              cornerHandles:             true,
              sideHandles:         true,
              drawBorders:         true,
              dragEdges:                 true,
              boxWidth:                  0,
              boxHeight:                 0,
              boundary:                  8,
              animationDelay:            20,
              swingSpeed:                3,
              allowSelect:         true,
              allowMove:                 true,
              allowResize:         true,
              minSelect:                 [ 0, 0 ],
              maxSize:                   [ 0, 0 ],
              minSize:                   [ 0, 0 ],
              // Here is the Callbacks and  Event Handlers
              onChange: function() { },
              onSelect: function() { }
       };
       var Myoptions = defaults;
       setOptionsFunction(Myopt );
      
       // Initializing some jQuery objects
       var $Myorigimg = $(Myobj);
       var $Myimg = $Myorigimg.clone().removeAttr('id').css({ position: 'absolute' });
       $Myimg.width($Myorigimg.width());
       $Myimg.height($Myorigimg.height());
       $Myorigimg.after($Myimg).hide();
       presize($Myimg,Myoptions.boxWidth,Myoptions.boxHeight);
       var boundx = $Myimg.width(),
              boundy = $Myimg.height(),
              $div = $('<div />')
                     .width(boundx).height(boundy)
                     .addClass(cssClass('holder'))
                     .css({
                           position: 'relative',
                           backgroundColor: Myoptions.bgColor
                     }).insertAfter($Myorigimg).append($Myimg);
       ;
      
       if (Myoptions.addClass) $div.addClass(Myoptions.addClass);
            var $img2 = $('<Myimg />')
                     .attr('src',$Myimg.attr('src'))
                     .css('position','absolute')
                     .width(boundx).height(boundy) ;
       var $Myimg_holder = $('<div />')
              .width(pct(100)).height(pct(100))
              .css({
                     zIndex: 310,
                     position: 'absolute',
                     overflow: 'hidden'
              })
              .append($img2)
       ;
       var $hdl_holder = $('<div />')/*{{{*/
              .width(pct(100)).height(pct(100))
              .css('zIndex',320);
       var $sel = $('<div />')
              .css({
                     position: 'absolute',
                     zIndex: 300
              })
              .insertBefore($Myimg)
              .append($Myimg_holder,$hdl_holder)
       ;
       var bound = Myoptions.boundary;
       var $Mytrk = newTrackerFunction().width(boundx+(bound*2)).height(boundy+(bound*2))
              .css({ position: 'absolute', top: px(-bound), left: px(-bound), zIndex: 290 })
              .mousedown(newSelectionFunction); 
      
      
       // Setting more variables to store data
       var Myxlimit, Myylimit, Myxmin, Myymin;
       var Myxscale, Myyscale, enabled = true;
       var MydocOffset  = getPosFunction($Myimg),
              //Here is some  Internal states
              btndown, lastcurs, dimmed, animating,
              shift_down;
             
       // Here is some internal modules
       var MyCoords  = function()
       {
              var Myx1 = 0, Myy1 = 0, Myx2 = 0, Myy2 = 0, ox, oy;
              function setPressed(Mypos)/*{{{*/
              {
                     var Mypos = rebound(Mypos);
                     Myx2 = Myx1 = Mypos[0];
                     Myy2 = Myy1 = Mypos[1];
              };
             
              function setCurrentFunction(Mypos)
              {
                     var Mypos = rebound(Mypos);
                     ox = Mypos[0] - Myx2;
                     oy = Mypos[1] - Myy2;
                     Myx2 = Mypos[0];
                     Myy2 = Mypos[1];
              };
             
              function getOffsetFunction()
              {
                     return [ ox, oy ];
              };
              /*}}}*/
              function moveOffsetFunction(offset)
              {
                     var ox = offset[0], oy = offset[1];
                     if (0 > Myx1 + ox) ox -= ox + Myx1;
                     if (0 > Myy1 + oy) oy -= oy + Myy1;
                     if (boundy < Myy2 + oy) oy += boundy - (Myy2 + oy);
                     if (boundx < Myx2 + ox) ox += boundx - (Myx2 + ox);
                     Myx1 += ox;
                     Myx2 += ox;
                     Myy1 += oy;
                     Myy2 += oy;
              };
             
              function getCornerFunction(Myord)
              {
                     var MyC = getFixedFunction();
                     switch(Myord)
                     {
                           case 'ne': return [ MyC.Myx2, MyC.y ];
                           case 'Mynw': return [ MyC.x, MyC.y ];
                           case 'se': return [ MyC.Myx2, MyC.Myy2 ];
                           case 'sw': return [ MyC.x, MyC.Myy2 ];
                     }
              };
             
              function getFixedFunction()
              {
                     if (!Myoptions.aspectRatio) return getRectFunction();
                     // You can optimize this function here
                     var aspect = Myoptions.aspectRatio,
                           min_x = Myoptions.minSize[0]/Myxscale,
                           min_y = Myoptions.minSize[1]/Myyscale,
                           max_x = Myoptions.maxSize[0]/Myxscale,
                           max_y = Myoptions.maxSize[1]/Myyscale,
                           Myrw  = Myx2 - Myx1,
                           Myrh = Myy2 - Myy1,
                           Myrwa = Math.abs(Myrw ),
                           Myrha  = Math.abs(Myrh),
                           Myreal_ratio = Myrwa / Myrha ,
                           Myxx, Myyy
                     ;
                     if (max_x == 0) { max_x = boundx * 10 }
                     if (max_y == 0) { max_y = boundy * 10 }
                     if (Myreal_ratio < aspect)
                     {
                           Myyy  = Myy2;
                           w = Myrha  * aspect;
                           Myxx = Myrw  < 0 ? Myx1 - w : w + Myx1;
                           if (Myxx < 0)
                           {
                                  Myxx = 0;
                                  h = Math.abs((Myxx - Myx1) / aspect);
                                  Myyy  = Myrh < 0 ? Myy1 - h: h + Myy1;
                           }
                           else if (Myxx > boundx)
                           {
                                  Myxx = boundx;
                                  h = Math.abs((Myxx - Myx1) / aspect);
                                  Myyy  = Myrh < 0 ? Myy1 - h : h + Myy1;
                           }
                     }
                     else
                     {
                           Myxx = Myx2;
                           h = Myrwa / aspect;
                           Myyy  = Myrh < 0 ? Myy1 - h : Myy1 + h;
                           if (Myyy  < 0)
                           {
                                  Myyy  = 0;
                                  w = Math.abs((Myyy  - Myy1) * aspect);
                                  Myxx = Myrw  < 0 ? Myx1 - w : w + Myx1;
                           }
                           else if (Myyy  >boundy)
                           {
                                  Myyy  = boundy;
                                  w = Math.abs(Myyy  - Myy1) * aspect;
                                  Myxx = Myrw  < 0 ? Myx1 - w : w + Myx1;
                           }
                     }
                     // Provide some magic effects
                     if(Myxx > Myx1) { //part of right side
                       if(Myxx - Myx1< min_x) {
                           Myxx = Myx1 + min_x;
                       } else if (Myxx - Myx1 > max_x) {
                           Myxx = Myx1 + max_x;
                       }
                       if(Myyy  >Myy1) {
                           Myyy  = Myy1 + (Myxx - Myx1)/aspect;
                       } else {
                           Myyy  = Myy1 - (Myxx - Myx1)/aspect;
                       }
                     } else if (Myxx< Myx1) { // part of left side
                       if(Myx1 - Myxx< min_x) {
                            Myxx = Myx1 - min_x
                       } else if (Myx1 - Myxx > max_x) {
                           Myxx = Myx1 - max_x;
                       }
                       if(Myyy  >Myy1) {
                           Myyy  = Myy1 + (Myx1 - Myxx)/aspect;
                       } else {
                           Myyy  = Myy1 - (Myx1 - Myxx)/aspect;
                       }
                     }
                     if(Myxx < 0) {
                           Myx1 -= Myxx;
                           Myxx = 0;
                     } else  if (Myxx > boundx) {
                           Myx1 -= Myxx - boundx;
                           Myxx = boundx;
                     }
                     if(Myyy  < 0) {
                           Myy1 -= Myyy ;
                           Myyy  = 0;
                     } else  if (Myyy  > boundy) {
                           Myy1 -= Myyy  - boundy;
                           Myyy  = boundy;
                     }
                     return last = makeObjFunction(flipCoordsFunction(Myx1,Myy1,Myxx,Myyy ));
              };
                           function rebound(p){
                     if (p[0] < 0) p[0] = 0;
                     if (p[1] < 0) p[1] = 0;
                     if (p[0] > boundx) p[0] = boundx;
                     if (p[1] > boundy) p[1] = boundy;
                     return [ p[0], p[1] ];
              };
             
              function flipCoordsFunction(Myx1,Myy1,Myx2,Myy2)
              {
                     var Myxa = Myx1, Myxb = Myx2, Myya = Myy1, Myyb = Myy2;
                     if (Myx2 < Myx1)
                     {
                           Myxa = Myx2;
                           Myxb = Myx1;
                     }
                     if (Myy2 < Myy1)
                     {
                           Myya = Myy2;
                           Myyb = Myy1;
                     }
                     return [ Math.round(Myxa), Math.round(Myya), Math.round(Myxb), Math.round(Myyb) ];
              };
              function getRectFunction()
              {
                     var xsize = Myx2 - Myx1;
                     var ysize = Myy2 - Myy1;
                     if (Myxlimit && (Math.abs(xsize) > Myxlimit))
                           Myx2 = (xsize > 0) ? (Myx1 + Myxlimit) : (Myx1 - Myxlimit);
                     if (Myylimit && (Math.abs(ysize) > Myylimit))
                           Myy2 = (ysize > 0) ? (Myy1 + Myylimit) : (Myy1 - Myylimit);
                     if (Myymin && (Math.abs(ysize) < Myymin))
                           Myy2 = (ysize > 0) ? (Myy1 + Myymin) : (Myy1 - Myymin);
                     if (Myxmin && (Math.abs(xsize) < Myxmin))
                           Myx2 = (xsize > 0) ? (Myx1 + Myxmin) : (Myx1 - Myxmin);
                     if (Myx1 < 0) { Myx2 -= Myx1; Myx1 -= Myx1; }
                     if (Myy1 < 0) { Myy2 -= Myy1; Myy1 -= Myy1; }
                     if (Myx2 < 0) { Myx1 -= Myx2; Myx2 -= Myx2; }
                     if (Myy2 < 0) { Myy1 -= Myy2; Myy2 -= Myy2; }
                     if (Myx2 > boundx) { var delta = Myx2 - boundx; Myx1 -= delta; Myx2 -= delta; }
                     if (Myy2 > boundy) { var delta = Myy2 - boundy; Myy1 -= delta; Myy2 -= delta; }
                     if (Myx1 > boundx) { var delta = Myx1 - boundy; Myy2 -= delta; Myy1 -= delta; }
                     if (Myy1 > boundy) { var delta = Myy1 - boundy; Myy2 -= delta; Myy1 -= delta; }
                     return makeObjFunction(flipCoordsFunction(Myx1,Myy1,Myx2,Myy2));
              };
             function makeObjFunction(a)
              {
                     return { x: a[0], y: a[1], Myx2: a[2], Myy2: a[3],
                           w: a[2] - a[0], h: a[3] - a[1] };
              };
             
              return {
                     flipCoordsFunction: flipCoordsFunction,
                     setPressed: setPressed,
                     setCurrentFunction: setCurrentFunction,
                     getOffsetFunction: getOffsetFunction,
                     moveOffsetFunction: moveOffsetFunction,
                     getCornerFunction: getCornerFunction,
                     getFixedFunction: getFixedFunction
              };
       }();
      
       var Selection = function()
       {
              var start, end, dragmode, Myawake, Myhdep = 370;
              var Myborders = { };
              var handle = { };
              var Myseehandles  = false;
              var Myhhs = Myoptions.handleOffset;
              /* Inserting here some draggable elements */
              // Inserting here some border divs for an outline
              if (Myoptions.drawBorders) {
                     Myborders = {
                                  top: insertBorderFunction('hline')
                                         .css('top',$.browser.msie?px(-1):px(0)),
                                  bottom: insertBorderFunction('hline'),
                                  left: insertBorderFunction('vline'),
                                  right: insertBorderFunction('vline')
                     };
              }
              // Inserting some handles for edges
              if (Myoptions.dragEdges) {
                     handle.t = insertDragbarFunction('n');
                     handle.b = insertDragbarFunction('s');
                     handle.r = insertDragbarFunction('e');
                     handle.l = insertDragbarFunction('w');
              }
              // Inserting here side handles
              Myoptions.sideHandles &&
                     createHandlesFunction(['n','s','e','w']);
              // Inserting here corner handles
              Myoptions.cornerHandles &&
                     createHandlesFunction(['sw','Mynw','ne','se']);
             
              // writing private methods
              function insertBorderFunction(type)/*{{{*/
              {
                     var Myjq = $('<div />')
                           .css({position: 'absolute', opacity: Myoptions.borderOpacity })
                           .addClass(cssClass(type));
                     $Myimg_holder.append(Myjq);
                     return Myjq;
              };
             
              function dragDivFunction(Myord,zi)
              {
                     var Myjq = $('<div />')
                           .mousedown(createDraggerFunction(Myord))
                           .css({
                                  cursor: Myord+'-resizeFunction',
                                  position: 'absolute',
                                  zIndex: zi
                           })
                     ;
                     $hdl_holder.append(Myjq);
                     return Myjq;
              };
             
              function insertHandleFunction(Myord)
              {
                     return dragDivFunction(Myord,Myhdep++)
                           .css({ top: px(-Myhhs+1), left: px(-Myhhs+1), opacity: Myoptions.handleOpacity })
                           .addClass(cssClass('handle'));
              };
             
              function insertDragbarFunction(Myord)
              {
                     var s = Myoptions.handleSize,
                           o = Myhhs,
                           h = s, w = s,
                           t = o, l = o;
                     switch(Myord)
                     {
                           case 'n': case 's': w = pct(100); break;
                           case 'e': case 'w': h = pct(100); break;
                     }
                     return dragDivFunction(Myord,Myhdep++).width(w).height(h)
                           .css({ top: px(-t+1), left: px(-l+1)});
              };
             
              function createHandlesFunction(li)
              {
                     for(i in li) handle[li[i]] = insertHandleFunction(li[i]);
              };
             
              function moveHandlesFunction(MyC)
              {
                     var midvert  = Math.round((MyC.h / 2) - Myhhs),
                           midhoriz = Math.round((MyC.w / 2) - Myhhs),
                           north = west = -Myhhs+1,
                           east = MyC.w - Myhhs,
                           south = MyC.h - Myhhs,
                           x, y;
                     'e' in handle&&
                           handle.e.css({ top: px(midvert), left: px(east) }) &&
                           handle.w.css({ top: px(midvert) }) &&
                           handle.s.css({ top: px(south), left: px(midhoriz) }) &&
                           handle.n.css({ left: px(midhoriz) });
                     'ne' in handle&&
                           handle.ne.css({ left: px(east) }) &&
                           handle.se.css({ top: px(south), left: px(east) }) &&
                           handle.sw.css({ top: px(south) });
                     'b' in handle&&
                           handle.b.css({ top: px(south) }) &&
                           handle.r.css({ left: px(east) });
              };
             
              function movetoFunction(x,y)
              {
                     $img2.css({ top: px(-y), left: px(-x) });
                     $sel.css({ top: px(y), left: px(x) });
              };
             
              function resizeFunction(w,h)
              {
                     $sel.width(w).height(h);
              };
             
              function refreshFunction()
              {
                     var MyC = MyCoords .getFixedFunction();
                     MyCoords .setPressed([MyC.x,MyC.y]);
                     MyCoords .setCurrentFunction([MyC.Myx2,MyC.Myy2]);
                     updateVisibleFunction();
              };
             
              //Writing here internal methods
              function updateVisibleFunction()
                     { if (Myawake) return update(); };
             
              function update()
              {
                     var MyC = MyCoords .getFixedFunction();
                     resizeFunction(MyC.w,MyC.h);
                     movetoFunction(MyC.x,MyC.y);
                     Myoptions.drawBorders &&
                           Myborders['right'].css({ left: px(MyC.w-1) }) &&
                                  Myborders['bottom'].css({ top: px(MyC.h-1) });
                     Myseehandles  && moveHandlesFunction(MyC);
                     Myawake || show();
                     Myoptions.onChange(unscaleFunction(MyC));
              };
             
              function show()
              {
                     $sel.show();
                     $Myimg.css('opacity',Myoptions.bgOpacity);
                     Myawake = true;
              };
              function releaseFunction()
              {
                     disableHandlesFunction();
                     $sel.hide();
                     $Myimg.css('opacity',1);
                     Myawake = false;
              };
              function showHandlesFunction()
              {
                     if (Myseehandles )
                     {
                           moveHandlesFunction(MyCoords .getFixedFunction());
                           $hdl_holder.show();
                     }
              };
              function enableHandlesFunction()
              {
                     Myseehandles  = true;
                     if (Myoptions.allowResize)
                     {
                           moveHandlesFunction(MyCoords .getFixedFunction());
                           $hdl_holder.show();
                           return true;
                     }
              };
             function disableHandlesFunction()
              {
                     Myseehandles  = false;
                     $hdl_holder.hide();
              };
              function animModeFunction(v)
              {
                     (animating = v) ? disableHandlesFunction(): enableHandlesFunction();
              };
              function doneFunction()
              {
                     animModeFunction(false);
                     refreshFunction();
              };
              var $track = newTrackerFunction().mousedown(createDraggerFunction('move'))
                           .css({ cursor: 'move', position: 'absolute', zIndex: 360 })
              $Myimg_holder.append($track);
              disableHandlesFunction();
              return {
                     updateVisibleFunction: updateVisibleFunction,
                     update: update,
                     releaseFunction: releaseFunction,
                     refreshFunction: refreshFunction,
                     setCursor: function (cursor) { $track.css('cursor',cursor); },
                     enableHandlesFunction: enableHandlesFunction,
                     enableOnly: function() { Myseehandles  = true; },
                     showHandlesFunction: showHandlesFunction,
                     disableHandlesFunction: disableHandlesFunction,
                     animModeFunction: animModeFunction,
                     doneFunction: doneFunction
              };
       }();
      var MyTracker = function()
       {
              var onMove           = function() { },
                     onDone        = function() { },
                     trackDoc      = Myoptions.trackDocument;
              if (!trackDoc)
              {
                     $Mytrk
                           .mousemove(trackMoveFunction)
                           .mouseup(trackUpFunction)
                           .mouseout(trackUpFunction)
                     ;
              }
              function toFrontFunction()
              {
                     $Mytrk.css({zIndex:450});
                     if (trackDoc)
                     {
                           $(document)
                                  .mousemove(trackMoveFunction)
                                  .mouseup(trackUpFunction)
                           ;
                     }
              }
             
              function toBackFunction()
              {
                     $Mytrk.css({zIndex:290});
                     if (trackDoc)
                     {
                           $(document)
                                  .unbind('mousemove',trackMoveFunction)
                                  .unbind('mouseup',trackUpFunction)
                           ;
                     }
              }
             
              function trackMoveFunction(e)
              {
                     onMove(mouseAbsFunction(e));
              };
             
              function trackUpFunction(e)
              {
                     e.preventDefault();
                     e.stopPropagation();
                     if (btndown)
                     {
                           btndown = false;
                           onDone(mouseAbsFunction(e));
                           Myoptions.onSelect(unscaleFunction(MyCoords .getFixedFunction()));
                           toBackFunction();
                           onMove = function() { };
                           onDone = function() { };
                     }
                     return false;
              };
               function activateHandlersFunction(move,doneFunction)
              {
                     btndown = true;
                     onMove = move;
                     onDone = doneFunction;
                     toFrontFunction();
                     return false;
              };
              function setCursor(t) { $Mytrk.css('cursor',t); };
              $Myimg.before($Mytrk);
              return {
                     activateHandlersFunction: activateHandlersFunction,
                     setCursor: setCursor
              };
       }();
      
       var KeyManager = function()
       {
              var $keymgr = $('<input type="radio" />')
                           .css({ position: 'absolute', left: '-30px' })
                           .keypress(parseKeyFunction)
                           .blur(onBlur),
                     $keywrap = $('<div />')
                           .css({
                                  position: 'absolute',
                                  overflow: 'hidden'
                           })
                           .append($keymgr)
              ;
              function watchKeys()
              {
                     if (Myoptions.keySupport)
                     {
                           $keymgr.show();
                           $keymgr.focus();
                     }
              };
             
              function onBlur(e)
              {
                     $keymgr.hide();
              };
              function doNudgeFunction(e,x,y)
              {
                     if (Myoptions.allowMove) {
                           MyCoords .moveOffsetFunction([x,y]);
                           Selection.updateVisibleFunction();
                     };
                     e.preventDefault();
                     e.stopPropagation();
              };
             
              function parseKeyFunction(e)
              {
                     if (e.ctrlKey) return true;
                     shift_down = e.shiftKey ? true : false;
                     var nudge = shift_down ? 10 : 1;
                     switch(e.keyCode)
                     {
                           case 37: doNudgeFunction(e,-nudge,0); break;
                           case 39: doNudgeFunction(e,nudge,0); break;
                           case 38: doNudgeFunction(e,0,-nudge); break;
                           case 40: doNudgeFunction(e,0,nudge); break;
                           case 27: Selection.releaseFunction(); break;
                           case 9: return true;
                     }
                     return nothing(e);
              };
             
             
              if (Myoptions.keySupport) $keywrap.insertBefore($Myimg);
              return {
                     watchKeys: watchKeys
              };
       }();
      
      
       //Writing some internal methods
       function px(n) { return '' + parseInt(n) + 'px'; };
       function pct(n) { return '' + parseInt(n) + '%'; };
       function cssClass(cl) { return Myoptions.baseClass + '-' + cl; };
       function getPosFunction(Myobj)
       {
              // Here some updated datas
              var Mypos = $(Myobj).offset();
              return [ Mypos.left, Mypos.top ];
       };
      
       function mouseAbsFunction(e)
       {
              return [ (e.pageX - MydocOffset [0]), (e.pageY - MydocOffset [1]) ];
       };
      
       function myCursor(type)
       {
              if (type != lastcurs)
              {
                     MyTracker.setCursor(type);
                    
                     lastcurs = type;
              }
       };
      
       function startDragModeFunction(mode,Mypos)
       {
              MydocOffset  = getPosFunction($Myimg);
              MyTracker.setCursor(mode=='move'?mode:mode+'-resizeFunction');
              if (mode == 'move')
                     return MyTracker.activateHandlersFunction(createMoverFunction(Mypos), doneSelectFunction);
              var Myfc = MyCoords .getFixedFunction();
              var Myopp = oppLockCornerFunction(mode);
              var Myopc = MyCoords .getCornerFunction(oppLockCornerFunction(Myopp));
              MyCoords .setPressed(MyCoords .getCornerFunction(Myopp));
              MyCoords .setCurrentFunction(Myopc);
              MyTracker.activateHandlersFunction(dragmodeHandlerFunction(mode,Myfc),doneSelectFunction);
       };
      
       function dragmodeHandlerFunction(mode,f)
       {
              return function(Mypos) {
                     if (!Myoptions.aspectRatio) switch(mode)
                     {
                           case 'e': Mypos[1] = f.Myy2; break;
                           case 'w': Mypos[1] = f.Myy2; break;
                           case 'n': Mypos[0] = f.Myx2; break;
                           case 's': Mypos[0] = f.Myx2; break;
                     }
                     else switch(mode)
                     {
                           case 'e': Mypos[1] = f.y+1; break;
                           case 'w': Mypos[1] = f.y+1; break;
                           case 'n': Mypos[0] = f.x+1; break;
                           case 's': Mypos[0] = f.x+1; break;
                     }
                     MyCoords .setCurrentFunction(Mypos);
                     Selection.update();
              };
       };
      
       function createMoverFunction(Mypos)
       {
              var lloc = Mypos;
              KeyManager.watchKeys();
              return function(Mypos)
              {
                     MyCoords .moveOffsetFunction([Mypos[0] - lloc[0], Mypos[1] - lloc[1]]);
                     lloc = Mypos;
                    
                     Selection.update();
              };
       };
       function oppLockCornerFunction(Myord)
       {
              switch(Myord)
              {
                     case 'n': return 'sw';
                     case 's': return 'Mynw';
                     case 'e': return 'Mynw';
                     case 'w': return 'ne';
                     case 'ne': return 'sw';
                     case 'Mynw': return 'se';
                     case 'se': return 'Mynw';
                     case 'sw': return 'ne';
              };
       };
      
       function createDraggerFunction(Myord)
       {
              return function(e) {
                     if (Myoptions.disabled) return false;
                     if ((Myord == 'move')&& !Myoptions.allowMove) return false;
                     btndown = true;
                     startDragModeFunction(Myord,mouseAbsFunction(e));
                     e.stopPropagation();
                     e.preventDefault();
                     return false;
              };
       };
      
       function presize($Myobj,w,h)
       {
              var Mynw = $Myobj.width(), Mynh = $Myobj.height();
              if ((Mynw > w) && w > 0)
              {
                     Mynw = w;
                     Mynh = (w/$Myobj.width()) * $Myobj.height();
              }
              if ((Mynh > h) && h > 0)
              {
                     Mynh = h;
                     Mynw = (h/$Myobj.height()) * $Myobj.width();
              }
              Myxscale = $Myobj.width() / Mynw;
              Myyscale = $Myobj.height() / Mynh;
              $Myobj.width(Mynw).height(Mynh);
       };
      
       function unscaleFunction(MyC)
       {
              return {
                     x: parseInt(MyC.x * Myxscale), y: parseInt(MyC.y * Myyscale),
                     Myx2: parseInt(MyC.Myx2 * Myxscale), Myy2: parseInt(MyC.Myy2 * Myyscale),
                     w: parseInt(MyC.w * Myxscale), h: parseInt(MyC.h * Myyscale)
              };
       };
      
       function doneSelectFunction(Mypos)
       {
              var MyC = MyCoords .getFixedFunction();
              if (MyC.w > Myoptions.minSelect[0] && MyC.h >Myoptions.minSelect[1])
              {
                     Selection.enableHandlesFunction();
                     Selection.doneFunction();
              }
              else
              {
                     Selection.releaseFunction();
              }
              MyTracker.setCursor( Myoptions.allowSelect?'crosshair':'default' );
       };
      
       function newSelectionFunction(e)
       {
              if (Myoptions.disabled) return false;
              if (!Myoptions.allowSelect) return false;
              btndown = true;
              MydocOffset  = getPosFunction($Myimg);
              Selection.disableHandlesFunction();
              myCursor('crosshair');
              var Mypos = mouseAbsFunction(e);
              MyCoords .setPressed(Mypos);
              MyTracker.activateHandlersFunction(selectDragFunction,doneSelectFunction);
              KeyManager.watchKeys();
              Selection.update();
              e.stopPropagation();
              e.preventDefault();
              return false;
       };
      
       function selectDragFunction(Mypos)
       {
              MyCoords .setCurrentFunction(Mypos);
              Selection.update();
       };
      
       function newTrackerFunction()
       {
              var Mytrk = $('<div></div>').addClass(cssClass('tracker'));
              $.browser.msie && Mytrk.css({ opacity: 0, backgroundColor: 'white' });
              return Mytrk;
       };
             //providing API methods
             
       function animateToFunction(a)
       {
              var Myx1 = a[0] / Myxscale,
                     Myy1 = a[1] / Myyscale,
                     Myx2 = a[2] / Myxscale,
                     Myy2 = a[3] / Myyscale;
              if (animating) return;
              var Myanimto = MyCoords .flipCoordsFunction(Myx1,Myy1,Myx2,Myy2);
              var MyC = MyCoords .getFixedFunction();
              var Myanimat = initcr = [ MyC.x, MyC.y, MyC.Myx2, MyC.Myy2 ];
              var Myinterv = Myoptions.animationDelay;
              var x = Myanimat[0];
              var y = Myanimat[1];
              var Myx2 = Myanimat[2];
              var Myy2 = Myanimat[3];
              var ix1 = Myanimto[0] - initcr[0];
              var iy1 = Myanimto[1] - initcr[1];
              var ix2 = Myanimto[2] - initcr[2];
              var iy2 = Myanimto[3] - initcr[3];
              var Mypcent = 0;
              var Myvelocity = Myoptions.swingSpeed;
              Selection.animModeFunction(true);
              var Myanimator = function()
              {
                     return function()
                     {
                           Mypcent += (100 - Mypcent) / Myvelocity;
                           Myanimat[0] = x + ((Mypcent / 100) * ix1);
                           Myanimat[1] = y + ((Mypcent / 100) * iy1);
                           Myanimat[2] = Myx2 + ((Mypcent / 100) * ix2);
                           Myanimat[3] = Myy2 + ((Mypcent / 100) * iy2);
                           if (Mypcent < 100) animateStartFunction();
                                  else Selection.doneFunction();
                           if (Mypcent >= 99.8) Mypcent = 100;
                           setSelectRawFunction(Myanimat);
                     };
              }();
              function animateStartFunction()
                     { window.setTimeout(Myanimator,Myinterv); };
              animateStartFunction();
       };
             function setSelectionFunction(rect)
       {
              setSelectRawFunction([rect[0]/Myxscale,rect[1]/Myyscale,rect[2]/Myxscale,rect[3]/Myyscale]);
       };
      
       function setSelectRawFunction(l)
       {
              MyCoords .setPressed([l[0],l[1]]);
              MyCoords .setCurrentFunction([l[2],l[3]]);
              Selection.update();
       };
      
       function setOptionsFunction(Myopt )
       {
              if (typeof(Myopt ) != 'object') Myopt  = { };
              Myoptions = $.extend(Myoptions,Myopt );
              if (typeof(Myoptions.onChange)!=='function')
                     Myoptions.onChange = function() { };
              if (typeof(Myoptions.onSelect)!=='function')
                     Myoptions.onSelect = function() { };
       };
      
       function tellSelectFunction()
       {
              return unscaleFunction(MyCoords .getFixedFunction());
       };
      
       function tellScaledFunction()
       {
              return MyCoords .getFixedFunction();
       };
      
       function setOptionsNewFunction(Myopt )
       {
              setOptionsFunction(Myopt );
              MyinterfaceUpdate();
       };
      
       function disableCropFunction()
       {
              Myoptions.disabled = true;
              Selection.disableHandlesFunction();
              Selection.setCursor('default');
              MyTracker.setCursor('default');
       };
      
       function enableCropFunction()
       {
              Myoptions.disabled = false;
              MyinterfaceUpdate();
       };
      
       function cancelCropFunction()
       {
              Selection.doneFunction();
              MyTracker.activateHandlersFunction(null,null);
       };
      
       function destroyFunction()
       {
              $div.remove();
              $Myorigimg.show();
       };
      
       function MyinterfaceUpdate(alt)
       //Here This method will tweaks the interface based on Myoptions object only.
       //It Called when Myoptions are get changed and at the end of initialization.
       {
              Myoptions.allowResize ?
                     alt?Selection.enableOnly():Selection.enableHandlesFunction():
                     Selection.disableHandlesFunction();
              MyTracker.setCursor( Myoptions.allowSelect? 'crosshair': 'default' );
              Selection.setCursor( Myoptions.allowMove? 'move': 'default' );
              $div.css('backgroundColor',Myoptions.bgColor);
              if ('setSelectionFunction' in Myoptions) {
                     setSelectionFunction(Myopt .setSelectionFunction);
                     Selection.doneFunction();
                     delete(Myoptions.setSelectionFunction);
              }
              if ('trueSize' in Myoptions) {
                     Myxscale = Myoptions.trueSize[0] / boundx;
                     Myyscale = Myoptions.trueSize[1] / boundy;
              }
              Myxlimit = Myoptions.maxSize[0] || 0;
              Myylimit = Myoptions.maxSize[1] || 0;
              Myxmin = Myoptions.minSize[0] || 0;
              Myymin = Myoptions.minSize[1] || 0;
              if ('outerImage' in Myoptions)
              {
                     $Myimg.attr('src',Myoptions.outerImage);
                     delete(Myoptions.outerImage);
              }
              Selection.refreshFunction();
       };
      
       $hdl_holder.hide();
       MyinterfaceUpdate(true);
      
       var api = {
              animateToFunction: animateToFunction,
              setSelectionFunction: setSelectionFunction,
              setOptionsFunction: setOptionsNewFunction,
              tellSelectFunction: tellSelectFunction,
              tellScaledFunction: tellScaledFunction,
              disable: disableCropFunction,
              enable: enableCropFunction,
              cancel: cancelCropFunction,
              focus: KeyManager.watchKeys,
              getBounds: function() { return [ boundx * Myxscale, boundy * Myyscale ]; },
              getWidgetSize: function() { return [ boundx, boundy ]; },
              releaseFunction: Selection.releaseFunction,
              destroyFunction: destroyFunction
       };
       $Myorigimg.data('Jcrop',api);
       return api;
};
$.fn.Jcrop = function(Myoptions)
{
       function attachWhenDoneFunction(from)
       {
              var Myloadsrc = Myoptions.useImg || from.src;
              var Myimg = new Image();
              Myimg.onload = function() { $.Jcrop(from,Myoptions); };
              Myimg.src = Myloadsrc;
       };
      
       if (typeof(Myoptions) !== 'object') Myoptions = { };
       // Iterating over each object as well as attaching Jcrop
       this.each(function()
       {
              // checking for If we already have attach to this object
              if ($(this).data('Jcrop'))
              {
                     // we can request the api this way
                     if (Myoptions == 'api') return $(this).data('Jcrop');
                     // else just reset
                     else $(this).data('Jcrop').setOptionsFunction(Myoptions);
              }
              // if it is not attached then preload and attach it
              else attachWhenDoneFunction(this);
       });
       // retuning this for chainable plugin
       return this;
};
})(jQuery);

 MyCropPage.aspx:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyCropPage.aspx.cs" Inherits="MyCropPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Cropping image with jquery and ASP.NET By Shibashish Mohanty</title>
    <link rel="stylesheet" href="Mystylefolder/jcrop.css" type="text/css" />
    <script src="Myjsfolder/jquery.min.Myjsfolder" type="text/javascript"></script>
    <script src="Myjsfolder/jquery.Jcrop.Myjsfolder" type="text/javascript"></script>
    <script src="Myjsfolder/crop.Myjsfolder" type="text/javascript"></script>
</head>
<body onload="Init();">
    <form id="form1" runat="server">
    <table>
        <tr>
            <td>My Original image
                <div Mystylefolder="width: 300px; height: 300px; overflow: auto; border: solid 1px black;
                    padding: 10px; margin-bottom: 5px;" id="imgContainer">
                    <Myimg src="images/Shibashish.jpg" alt="My auto" title="This is  my auto image" id="MyoriginalImage" />
                </div>
                <div>
                    X1
                    <input type="text" size="4" id="Myx1" name="Myx1" class="coor" readonly="readonly" />
                    Y1
                    <input type="text" size="4" id="Myy1" name="Myy1" class="coor" readonly="readonly" />
                    X2
                    <input type="text" size="4" id="Myx2" name="Myx2" class="coor" readonly="readonly" />
                    Y2
                    <input type="text" size="4" id="Myy2" name="Myy2" class="coor" readonly="readonly" />
                    WIDTH
                    <input type="text" size="4" id="w" name="w" class="coor" readonly="readonly" />
                    HEIGHT
                    <input type="text" size="4" id="h" name="h" class="coor" readonly="readonly" />
                </div>
                <div>
                    <asp:Button runat="server" ID="CroppedBtn" OnClick="CroppedBtn_Click" Text="Crop" OnClientClick="return ValidateSelectedPortion();" />
                </div>
            </td>
            <td Mystylefolder="vertical-align:top;">
             This is your Cropped image:
                <div Mystylefolder="width: 300px; height: 300px; overflow: auto; border: solid 1px black;
                    padding: 10px; margin-bottom: 5px;">
                    <asp:Literal runat="server" ID="LabelCrpImage"></asp:Literal>
                </div>
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

 MyCropPage.aspx.cs

using System;
using System.Web;
using System.Web.UI;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
public partial class MyCropPage : System.Web.UI.Page
{
    protected void CroppedBtn_Click(object sender, EventArgs e)
    {
        int X1 = Convert.ToInt32(Request.Form["Myx1"]);
        int Y1 = Convert.ToInt32(Request["Myy1"]);
//Taking input and converting to integer value
        int X2 = Convert.ToInt32(Request.Form["Myx2"]);
        int Y2 = Convert.ToInt32(Request.Form["Myy2"]);
        int X = System.Math.Min(X1, X2);
        int Y = System.Math.Min(Y1, Y2);
        int w = Convert.ToInt32(Request.Form["w"]);
        int h = Convert.ToInt32(Request.Form["h"]);
        // It may be any image types like(jpg,jpeg,png,gif) from the local server
        string MyoriginalFile = Server.MapPath("~/images/miautito.jpg");
        using (Image Myimg = Image.FromFile(MyoriginalFile))
        {
            using (System.Drawing.Bitmap _Mybitmap = new System.Drawing.Bitmap(w, h))
            {
                _Mybitmap.SetResolution(Myimg.HorizontalResolution, Myimg.VerticalResolution);
                using (Graphics _Mygraphic = Graphics.FromImage(_Mybitmap))
                {
                    _Mygraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    _Mygraphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    _Mygraphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                    _Mygraphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    _Mygraphic.DrawImage(Myimg, 0, 0, w, h);
                    _Mygraphic.DrawImage(Myimg, new Rectangle(0, 0, w, h), X, Y, w, h, GraphicsUnit.Pixel);
                    string Myextension = Path.GetExtension(MyoriginalFile);
                    string fileCropped = Guid.NewGuid().ToString();
                    string MyFolderPath = Server.MapPath("~/ImageCropped/");
                    // If your image is a gif file, then it will change it into png
                    if (Myextension.EndsWith("gif", StringComparison.OrdinalIgnoreCase))
                    {
                        Myextension = ".png";
                    }
                    string myFullPathName = string.Concat(MyFolderPath, fileCropped, Myextension);
                    using (EncoderParameters encoderParameters = new EncoderParameters(1))
                    {
                        encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
                        _Mybitmap.Save(myFullPathName, MethodGetImageCode(Myextension), encoderParameters);
                    }
                    LabelCrpImage.Text = string.Format("<Myimg src='ImageCropped/{0}' alt='Cropped image'>", fileCropped + Myextension);
                }
            }
        }
    }
    public static ImageCodecInfo MethodGetImageCode(string Myextension)
    {
        Myextension = Myextension.ToUpperInvariant();
        ImageCodecInfo[] MyCodecs = ImageCodecInfo.GetImageEncoders();
        foreach (ImageCodecInfo MyCodec in MyCodecs)
        {
            if (MyCodec.FilenameExtension.Contains(Myextension))
            {
                return MyCodec;
            }
        }
        return MyCodecs[1];
    }
}
 

 Hope you will like this article
Keep coding...... 

 

Thanks Shibashish Mohanty

1 comment:

  1. hii sir ,can u tell me how to make master page in ASP.net with C# and crystal Report.
    plz help me...........sir............):

    ReplyDelete

Please don't spam, spam comments is not allowed here.

.

ShibashishMnty
shibashish mohanty