Use the imgAreaSelect plug-in of jquery to crop images.
Cropping and saving uploaded images is a common task in Web applications, now, with the help of jquery's imgareaselect plug-in and PHP's GD library, you can easily implement this previously tricky feature. Let's take a look at its implementation steps:
1. Package the cssfile (imgareaselect-default.css) and jquery. imgareaselect. js.
2. html code (image elements to be cropped)
3. Data Operations of imgAreaSelect
$('#selectbanner').imgAreaSelect({ selectionColor: 'blue', x1:0, y1:0, x2: 950,
maxWidth:950,minWidth:950,y2:400,minHeight:400,maxHeight:400,
selectionOpacity: 0.2 , onSelectEnd: preview });
In this way, the cropping function can be used in the Image Element. After the box is selected, we have to write code to save the selected image. The following operations are performed when you click a crop button after the image area is determined:
// Cropping confirmation operation
$ ("# SliceButton"). click (function (){
Var pic = $ ('# selectbanner'). attr ('src ');
Var x, y, w, h;
$. Post (
"/Template/sliceBanner ",
{
X: $ ('# selectbanner'). data ('x '),
Y: $ ('# selectbanner'). data ('y '),
W: $ ('# selectbanner'). data ('W '),
H: $ ('# selectbanner'). data ('H '),
Pic: pic
},
Function (data ){
// Load the cropped image to the original position
If (data ){
$ ('# Selectbanner'). attr (pic );
}
}
);
});
// Set the selection information of the Selection box
// Use the data method in jquery to save the generated data
Function preview (img, selection ){
$ ('# Selectbanner'). data ('x', selection. x1 );
$ ('# Selectbanner'). data ('y', selection. y1 );
$ ('# Selectbanner'). data ('w', selection. width );
$ ('# Selectbanner'). data ('h', selection. height );
}
4. Main PHP code:
// Use the GD library for Cropping
Function sliceBanner (){
$ X = (int) $ _ POST ['X'];
$ Y = (int) $ _ POST ['y'];
$ W = (int) $ _ POST ['W'];
$ H = (int) $ _ POST ['H'];
$ Filename = trim ($ _ POST ['pic ']);
If (isset ($ filename )){
$ UploadBanner = '/temp'. $ filename;
$ SliceBanner = 'upload/'. $ filename;
$ Src_pic = getImageHander ($ uploadBanner );
If (! $ Src_pic ){
Echo 0; exit;
}
$ Dst_pic = imagecreatetruecolor ($ w, $ h );
Imagecopyresampled ($ dst_pic, $ src_pic, 0, 0, $ x, $ y, $ w, $ h, $ w, $ h );
Imagejpeg ($ dst_pic, $ sliceBanner );
Imagedestroy ($ src_pic );
Imagedestroy ($ dst_pic );
Echo 1; exit;
}
Echo 0; exit;
}
function getImageHander ($url) {
$size=@getimagesize($url);
switch($size['mime']){
case 'image/jpeg': $im = imagecreatefromjpeg($url);break;
case 'image/gif' : $im = imagecreatefromgif($url);break;
case 'image/png' : $im = imagecreatefrompng($url);break;
default: $im=false;break;
}
return $im;
}
1. Introduction
ImgAreaSelect is a jQuery plug-in that allows you to drag and drop a part of an image, a very fashion. In addition, you can apply other website technologies, such as drag-and-drop operations and image editing, on the basis of this image area.
2. Basic usage
This plug-in is called Based on the imgAreaSelect () method on jQuery. It operates on images in elements of HTML.
Copy the Code as follows:
<Script type = "text/javascript">
$ (Document). ready (function (){
$ ('Img # photo '). imgAreaSelect ({
Handles: true,
OnSelectEnd: someFunction
});
});
</Script>
If there is more than one img element in the jQuery object, the plug-in will apply this method one by one to the elements in it. In fact, this method is not only applied to img elements, but also supports any block-level elements (such as div elements with image backgrounds ).
Similar to other jQuery plug-ins, this plug-in can be initialized in the $ (document). ready () or $ (window). load () handle.
3. Options
You can customize this plug-in many aspects. You can use the plug-in options to achieve this purpose (these options will take effect during plug-in Initialization ). These options include:
Option |
Description |
AspectRatio |
Aspect ratio, which will remain unchanged in the future. E.g. "4: 3" |
AutoHide |
If it is set to true, the region disappears after selection. Default: false |
ClassPrefix |
Prefix of the plug-in element (see Figure 5. Elements and classes) Default: imgareaselect |
Disable |
If it is set to true, this plug-in will not work (but the image is still visible) |
Enable |
If it is set to true, the plug-in will take effect again. |
FadeSpeed |
If it is set to a certain number greater than zero, the plug-in "Fade-in/fade-out" Default: true |
Handles |
If it is set to true, the change box is displayed when the size is changed (that is, the corner is small "rectangle ") Default: false |
Hide |
If this parameter is set to true, the selection box is hidden. |
ImageHeight |
The actual height of the image (because it may have been scaled by CSS) |
ImageWidth |
The true width of the image (because CSS may have bloomed) |
Instance |
If it is set to true, the imgAreaSelect () function returns a reference to the image of the selected region, so that you can further use the API. (For details, see 8. API method) |
Keys |
Enable/disable keyboard support (For details, refer to 7. keyboard Support) Default: false |
MaxHeight |
Restrict the selection box (in pixels) and set the maximum, minimum height, and width. |
MaxWidth |
MinHeight |
MinWidth |
Movable |
Set whether to support selection box Movement Default: true |
Parent |
Specify the parent element appended to this plug-in by default Default: body |
Persistent |
If this parameter is set to true, a new option will start when you click "out-of-range" (in other words, whether to allow users to move or scale only the selected area) Default: false |
Remove |
If it is set to true, the plug-in will be completely removed |
Resizable |
Determines whether the size of the selected region can be changed. Default: true |
ResizeMargin |
The "changeable size" mode is enabled when the selected area width exceeds several pixels. |
Show |
If this parameter is set to true, the selected region is visible. |
X1 Y1 |
Select the coordinates in the upper-left corner of the box during initialization. |
X2 Y2 |
Select coordinates in the lower-right corner of the box during initialization |
ZIndex |
Set the z-index value of the element to which this plug-in applies. Generally, imgAreaSelect can automatically calculate its value, but in rare cases it is necessary to set it. |
OnInit |
Functions called when the plug-in is initialized (For details, refer to 6. Callback functions) |
OnSelectStart |
The function called at the start of selection (For details, refer to 6. Callback Function) |
OnSelectChange |
The function called when the selected region is changed (For details, refer to 6. callback function) |
OnSelectEnd |
The function called at the end of the selection (For details, refer to 6. Callback Function) |
4. Style Sheets
With the release of the plug-in, there are three style sheets:
Imgareaselect-default.css-this is the default style sheet,
Imgareaselect-animated.css-This style is basically the same as the default style sheet, but it lets the selection area border change
Imgareaselect-deprecated.css-use this style sheet only when you want to use an option that you don't agree.
You only need to add a style sheet in the html header. The css folder also contains four GIF images, which are used to display borders.
5. Elements and Classes
This plugin creates several div elements to indicate the selected area, including the border, adjustable handle, and unselected area. These elements have already specified specific class names, so you can obtain and operate them through CSS or jQuery selector.
Class Name |
Specified object |
Imgareaselect-selection |
Selected Region |
Imgareaselect-border1 Imgareaselect-border2 Imgareaselect-border3 Imgareaselect-border4 |
Select the four borders of the area, composed of four div |
Imgareaselect-handle |
Adjustable handle that can be changed (four or eight divs are not displayed if no enable is enabled) |
Imgareaselect-outer |
Area not selected, composed of four divs |
The following objects demonstrate how these elements of the plug-in are arranged:
The prefix "imgareaselect" is the default prefix, which can be modified using the "classPrefix" option. This is especially useful when many selection boxes need to be operated separately (such as modifying the style.
6. Callback Function
The callback function (when onInit, onSelectStart, onSelectChange or onSelectEnd options are set) receives two parameters. The first option is the reference of the image applied by the plug-in, and the other is to present the selected object, this object has six properties.
Nature |
Description |
X1 Y1 |
Select coordinates in the upper left corner of the area |
X2 Y2 |
Select coordinates in the lower-right corner of the area |
Width |
Select the area width |
Height |
Select the region height |
For ease of understanding, the following is an example of the callback function executed after selection:
$ ('Img # photo '). imgAreaSelect ({
OnSelectEnd: function (img, selection ){
Alert ('width: '+ selection. width +'; height: '+ selection. height );
}
});
7. keyboard support
If the option "keys" is set to true, we can move the selection box by pressing the key on the keyboard. The following keys can be used. The default functions are as follows:
Buttons |
Action |
Direction key |
Move the selection area in 10 pixels each time |
Shift + direction key |
Each time the selection area is moved in 1 pixel |
Ctrl + direction key |
Each time, the selection area is expanded in 10 pixels. |
Ctrl + Shift + direction key |
Each time the selection area is expanded in 1 pixel |
You can also set the "keys" option to overwrite the default key setting. The object has the following attributes:
Attribute |
Description |
Direction key |
Set direction keys |
Shift |
Set the Shift key function |
Ctrl |
Set the Ctrl key function |
Alt |
Set the Alt key |
Each attribute sets a value (in pixels, the value must not be less than 1), indicating how many pixels are moved/changed when the key is pressed, you can also specify the value as "string" to specify the "resize" mode. For example:
$ ('Img # example '). imgAreaSelect ({
Keys: {arrows: 15, ctrl: 5, shift: 'resize '}
});
In this example, it is set to "the direction key moves the selection area by 15 pixels, press Ctrl to move 5 pixels, and press Shift to switch to the resize mode ".
If there is more than one image, and you have modified the key settings, the custom settings will be applied to only one image. Generally, when "Activate" (click with the mouse) an image, the Custom button settings are used.
8. API methods
This plug-in also provides several API methods to expand its applications, and can be used together with other web applications through these API methods.
To use these methods, you first need a plug-in object, which can call the imgAreaSelect () function and set its option "instance" to true:
Var ias = $ ('# photo'). imgAreaSelect ({instance: true });
Now you can use this object to call public methods. For example, set a default predefined range:
Ias. setSelection (50, 50,150,200, true );
Ias. setOptions ({show: true });
Ias. update ();
You can use these API methods as long as the initialization is complete. These API methods are listed below:
Method |
Description |
GetOptions |
GetOptions () -- Return the configuration of the current option Returns: An object that contains the configuration of the current option (generally a JSON object) |
SetOptions |
SetOptions (newOptions) -- Set plug-in Options Parameters: NewOptions-option configuration object (generally a JSON object) |
GetSelection |
GetSelection ([noScale]) -- Obtain the current constituency Parameters: NoScale (optional)-if it is set to true, no scaling is performed on the returned constituency. Return Value: Select objects in the region |
SetSelection |
SetSelection (x1, y1, x2, y2, [noScale]) -- Set the currently selected region Parameters: X1-select the X coordinate in the upper left corner of the area Y1-select Y coordinate in the upper left corner of the area X2-select the X coordinate in the lower right corner of the area Y2-select Y coordinate in the lower right corner of the area NoScale (optional)-If set to true, the image is not scaled. Note: This method only sets the selection region in the plug-in and does not immediately observe the change of the constituency. If you need to immediately display the changed region, you must use setSelect () call the update () function and set the show option to true. |
CancelSelection |
CancelSelection () -- Cancel the current selection Note: This method hides the "select/not selected" area, so you do not have to call the update () function. |
Update |
Update ([resetKeyPress]) -- Update plug-in configuration Parameters: ResetKeyPress (optional)-if it is set to false, the keys of this instance will be reset (that is, unavailable) |
Ii. Simple instances
1. width or height
The minWidth, minHeight, maxWidth, and maxHeight options allow you to set the range of a selection. In this example, the maximum image range is x px.
$ (Document). ready (function (){
$ ('# Ladybug_ant'). imgAreaSelect ({maxWidth: 200, maxHeight: 150, handles: true });
});
2. Fixed Aspect Ratio
Configure the aspectRatio option. set it to "4: 3 ":
$ (Document). ready (function (){
$ ('# Bee'). imgAreaSelect ({aspectRatio: '4: 3', handles: true });
});
3. Set the initial option Area
Configure the options x1, y1, x2, and y2:
$ (Document). ready (function (){
$ ('# Duck'). imgAreaSelect ({x1: 120, y1: 90, x2: 280, y2: 210 });
});
Iii. Callback Function example
1. constituency Preview
In the following code snippet, The onSelectChange () callback function achieves the effect of selecting a region preview.
Official source code: http://odyniec.net/projects/imgareaselect/examples-callback.html
Function preview (img, selection ){
Var scaleX = 100/(selection. width | 1 );
Var scale= 100/(selection. height | 1 );
$ ('# Ferret + div> img'hangzhou.css ({
Width: Math. round (scaleX * 400) + 'px ',
Height: Math. round (scaleY * 300) + 'px ',
MarginLeft: '-' + Math. round (scaleX * selection. x1) + 'px ',
MarginTop: '-' + Math. round (scaleY * selection. y1) + 'px'
});
}
// Insert the same image after the original image using jQuery syntax
$ (Document). ready (function (){
$ ('')
. Css ({
Float: 'left ',
Position: 'relative ',
Overflow: 'ddy ',
Width: '100px ',
Height: '100px'
})
. InsertAfter ($ ('# ferret '));
$ ('# Ferret'). imgAreaSelect ({aspectRatio: '1: 1', onSelectChange: preview });
});
Because the preview window is x px, the preview image is enlarged when the window is smaller than PX. When the window is larger than PX, the preview image is reduced. These two types are as follows:
1. When the window is larger than 100px
2 when the window is smaller than 100px
It should be noted that this effect is a skill. The most important one is proportional scaling. it requires two images. The first image is the source image, and the second image is the image displayed after the selected area. The second image is generated using the selected coordinates + css on the first image, in fact, the two images are the same, but they only control the display area and zoom ratio of the second image through css. The evidence is as follows:
[Evidence 1] inserting "src" is also an image of "http://www.bkjia.com/uploads/allimg/140803/043SL248-2.jpg" Through insertAfter in the $ (document). ready () function. Note that the line of "overflow: 'hiddy' in this section is to hide the extra content of an image that is larger than PX.
[Evidence 2] In the preview () function, scaleX and scaleY are defined first, and their content is 100/selection. width (or height), that is, when selection. when the width is less than 100, this factor plays a role in amplification, and vice versa.
It is worth noting that:
The width and height of the actual graph in the callback function (300,400 here is the height of the actual graph, which should be adjusted according to the actual situation !), In the callback function, the width and height parameters must be set correctly. Otherwise, the selection deviation may occur.
2. Submit the coordinates of the selected area
To implement real functions, you must use server support, such as php asp aspx jsp. This means that the selection on the client is only the first step. If further processing is required, the coordinates of the selection must be submitted to the server. So how to implement it?
Create a commendation with four hidden domains:
Then, when initializing imgAreaSelect, use the onSelectEnd () callback function to assign the selected data to these hidden fields, as shown in the following code:
$ (Document). ready (function (){
$ ('# Ladybug'). imgAreaSelect ({
OnSelectEnd: function (img, selection ){
$ ('Input [name = "x1"] '). val (selection. x1 );
$ ('Input [name = "y1"] '). val (selection. y1 );
$ ('Input [name = "x2"] '). val (selection. x2 );
$ ('Input [name = "y2"] '). val (selection. y2 );
}
});
});
In this way, when you click "submit", the page will be uploaded to the server. If you use PHP, use $ _ POST ['x1 '] to obtain the corresponding coordinate data.