Support Mobile Clip Image plugin Jcrop (combined with webuploader upload)

Source: Internet
Author: User

(This tutorial includes the front-end implementation of picture cropping, the back end to get the cropping area and save)

Recently there is a demand, the public number upload images, support custom cropping.

Previously used a clip plug-in cropper, long time useless, do not know how to mobile operation compatibility, re-search from the Web more appropriate plug-ins

First tried the photoclip, this plug-in clipping area is fixed, can not customize the zoom (perhaps the demand is too hasty to study, or can modify the original file optimization this point), for the user experience is not good enough, so, give up

Then encountered a plug-in---jcrop, perfect in line with the needs, the project combined with the Baidu plugin Webuploader upload to obtain the original image, can be adapted to the mobile selection album/photo upload, get to select the photo set to Jcrop (Jcrop.setimage ( Response.url);) to crop

Jcrop Advantages:

    • unobtrusively all images (no intrusion, keep dom simple)
    • Supports wide-height proportional locking
    • Support Minsize/maxsize Settings
    • Supports callbacks when changing a selection or moving a selection (Callback)
    • Support to fine-tune selections with the keyboard
    • Create interactions via APIs, such as animation effects
    • CSS style support
    • Simple and convenient, JS and CSS easy to understand, ease of maintenance

Jcrop implementation very simple answer, is interested to continue to see the following:

1. Reference JS files and CSS files:

<script type= "Text/javascript" src= "@ (weixinconfig.resourceaddress) js/jcrop/jquery. Jcrop.js "></script>    <script type=" Text/javascript "src=" @ (weixinconfig.resourceaddress) js/jcrop/ Jquery.color.js "></script>    <link rel=" stylesheet "href=" @ (weixinconfig.resourceaddress) js/jcrop/ Jquery. Jcrop.css ">

2. Define clipping DOM, only need one IMG tag

<div id= "Jcropbox" style= "width:100%; height:90%; " >            <!--This was the image we 're attaching jcrop to--             </div>

3. Initialize Jcrop

// The default parameter initializes jcrop$ ("#jcropTarget"). Jcrop ();  

With just three steps above, you can crop a picture that supports moving, zooming, dragging and dropping.

You can also customize the presentation of the initialized Jcrop

$ (' #jcropTarget ').                Jcrop ({onchange:showcoords, onselect:showcoords, Onrelease:clearcoords, BOXWIDTH:JCROPW, Boxheight:jcroph, Handlesize:ismobile ()= = = 0? 28:15            }, function() {Jcrop= This; Jcrop.setselect ([130, 65, 130 + 350, 65 + 285]); Jcrop.setoptions ({bgfade:true, bgopacity:0.5, BgColor:' Black ', AddClass:' Jcrop-light ', Handleoffset:20                }); });

At the end of the article there are various parameter description tables, which do not do one by one explanations

function Showcoords (c) {                = c.x;                 = c.y;                 = c.w;                 = c.h;            };             function clearcoords () {                $ (' #coords input '). Val (');            };

To save the picture further, I took the x,y,width,height to get the cropped picture

Add a Crop button

<button id= "btnsavejcropimg" class= "Btnjcrop" > Cropping </button>

Register the Click event to pass the final trimmed x,y,w,h parameter to the backend for analysis and save

 // <summary>        ///Save the cropped new picture (capture the original image by X,y,w,h)/// </summary>        /// <param name= "x" ></param>        /// <param name= "y" ></param>        /// <param name= "W" ></param>        /// <param name= "h" ></param>        /// <param name= "filename" > filename, webuploader upload to the server's original image </param>        /// <returns></returns>[HttpPost] PublicJsonresult jcropuploadprocess (intXintYintWintHstringfileName) {            Try            {Viewbag.yearenduploadurl=Yearenduploadurl; //Save to Temp folder                stringPath ="/upload/yearend/"; stringLocalPath =HttpContext.Server.MapPath (path); if(!System.IO.Directory.Exists (LocalPath))                {System.IO.Directory.CreateDirectory (LocalPath); } LocalPath= HttpContext.Server.MapPath (path +"/temp"); if(!System.IO.Directory.Exists (LocalPath))                {System.IO.Directory.CreateDirectory (LocalPath); }                //Picture Path                stringOldPath =System.IO.Path.Combine (LocalPath, fileName); //New picture Path                stringNewPath =System.IO.Path.GetExtension (OldPath); NewPath= Oldpath.substring (0, oldpath.length-newpath.length) +"_new"+NewPath; //defining an intercept rectangleSystem.Drawing.Rectangle Croparea =NewSystem.Drawing.Rectangle (x, Y, W, h);//the size of the area to intercept//Loading PicturesSystem.Drawing.Image img = System.Drawing.Image.FromStream (NewSystem.IO.MemoryStream (System.IO.File.ReadAllBytes (OldPath))); //Defining Bitmap ObjectsSystem.Drawing.Bitmap Bmpimage =NewSystem.Drawing.Bitmap (IMG); //to CropSystem.Drawing.Bitmap Bmpcrop =Bmpimage.clone (Croparea, Bmpimage.pixelformat); //Save as new fileBmpcrop.save (NewPath); //Releasing Objectsimg.                Dispose ();                Bmpcrop.dispose (); //get file name + suffix                stringFilepathname =System.IO.Path.GetFileName (NewPath); returnJson (New{ret=0, Jsonrpc="2.0", id="ID", FilePath=filepathname, url= Yearenduploadurl +"temp/"+filepathname}); }            Catch(Exception ex) {returnJson (New{ret =1, Jsonrpc =2.0, error =New{Code =102, message = ex. Message}, id ="ID" }); }        }

Finally attach extension instructions

Options parameter Description

Name of parameter Default value Parameter description
Allowselect True Allow New Marquee
Allowmove True Allow marquee Movement
Allowresize True Allow marquee scaling
Trackdocument True
BaseClass "Jcrop" The base style name prefix. Description: class= "Jcrop-holder", only to change the jcrop.
AddClass Null Add a style. Assuming the class name is "Test", add the style to class= "Test Jcrop-holder"
BgColor "Black" Background color. Color keywords, HEX, RGB are available.
Bgopacity 0.6 Background transparency
Bgfade False Whether to use the background transition effect
Borderopacity 0.4 Marquee Border Transparency
Handleopacity 0.5 Zoom button Transparency
Handlesize 9 Zoom button Size
Handleoffset 5 The distance between the Zoom button and the border
Aspectratio 0 Marquee aspect ratio. Description: Width/height
Keysupport True Keyboard control is supported. Key list: Up or Down (move), ESC (cancel), Tab (jump out of crop box, to next)
Cornerhandles True Allow Corner scaling
Sidehandles True Allow four-sided scaling
Drawborders True Draw Border
Dragedges True Allow dragging borders
Fixedsupport True
Touchsupport Null
Boxwidth 0 Canvas width
Boxheight 0 Canvas height
Boundary 2 Boundary. Description: You can drag the mouse from the border to select the cropping area
Fadetime 400 Time to over effect
Animationdelay 20 Animation delay
Swingspeed 3 Transition speed
Minselect [0,0] Select the minimum size of the selection box. Note: If the box is smaller than the size, the selection is automatically deselected
MaxSize [0,0] Marquee Maximum Size
MinSize [0,0] Marquee Minimum Size
OnChange function () {} Events when the marquee changes
OnSelect function () {} Events when the marquee is selected
Onrelease function () {} Event when a marquee is deselected

API Method Description

Method Instructions for using the method
SetImage (String) Set (or change) the image. Example: Jcrop_api.setimage ("Newpic.jpg")
SetOptions (object) Set (or change) parameters in the same format as initialization setting parameters
Setselect (Array) Create a marquee with the parameter format: [X,y,x2,y2]
Animateto (Array) Create a marquee with the animation effect, the parameter format is: [X,y,x2,y2]
Release () Cancel Marquee
Disable () Disables Jcrop. Description: A marquee has not been cleared.
Enable () Enable Jcrop
Destroy () Remove Jcrop
Tellselect () Gets the value of the marquee (actual size). Example: Console.log (Jcrop_api.tellselect ())
Tellscaled () Gets the value of the marquee (interface size). Example: Console.log (jcrop_api.tellscaled ())
GetBounds () Get the actual size of the picture in the format: [W,h]
Getwidgetsize () Get the picture display size in the format: [W,h]
Getscalefactor () Gets the scale of the picture scale in the format: [W,h]

JQuery jcrop plugin Download (where CSS files are partially optimized)

Support Mobile Clip Image plugin Jcrop (combined with webuploader upload)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.