Based on Jquery+httphandler to achieve the image clipping effect code (for forum, SNS) _jquery

Source: Internet
Author: User

Body:
To make the hierarchy clear and easy to read, the whole solution is as follows:

Where Bitmapcutter.core is the server-side handler for the picture, the class diagram is:

For more information, see the Source notes:

Cutter is a crop object that stores data submitted by the client via Ajax.

Helper for the image processing class, including picture rollover (Rotateimage ()), picture cropping (Generatebitmap ()).

Callback the server-side image processing class by using cutter to encapsulate the data submitted by the client Ajax, and then call the helper method to complete the image processing.

Bitmapscissors is a httphandler that invokes the method in callback through the ' action ' returned by the client:


Note: A reflection is used here to dynamically invoke the method in the callback according to the ' action ' value, if you are not accustomed to it or think it is improper to change ...

Client Ajax submitted URL is "Scissors.axd", the actual bitmapscissors class (such as modified server-side handler, in Web.config according to the actual HttpHandler node configuration), this example:

Ok, let's start with the focus, $.fn.bitmapcutter plug-in implementation:

First to the effect of the picture, mark the Bitmapcutter in the DOM object, the amount, like just big wood fan more, come to Zhangloke:

Description

Holder for the original load container, when the original image is too large to display only part, by panning to view the images of the display area, holder for Div, set position style for relative, so that the original IMG (the same IMG object) Position style for absolute, you can control its left, the top value to the image of the translation display, note that holder overflow must be set to hidden, so that the IMG will be wrapped in holder, IMG Beyond the holder boundary will be hidden.

Cutter for the Intercept box, can drag and drop to select their own interest in the interception area, drag the area in the holder container, but also in the thumbimg (principle and holder+img the same) within the generation of thumbnails.

OPTs-functional area, providing all available function buttons, including: Zoom in, zoom out, move left, right, move up, move down, restore, rotate left, rotate right.

Info-photo element, used to display the aspect ratio of the current image to be intercepted.

Principle:

Familiar with CSS words should be easy to see, using relative positioning flexibility and JS control of the CSS.

Plug-in Description:

Because the plug-in code is more, here is the focus of the Talk:

1. Global variables:

Because of the frequent use of data and jquery objects throughout the cropping process, a global variable is defined to store.

$originalSize: The original image of the phase, in the first load of the original image acquisition, can not be changed, mainly for magnification, reduction and restore to provide a pair of basic data (long, wide).
$zoomValue: The current scaling ratio, synchronized when performing magnification or narrowing.
$thumbimg: The jquery object that crops the area thumbnail, which is assigned when the DOM is created.
$img: The original jquery object, acquired when the DOM is created.
$cutter: Crop areas are also acquired when the DOM is created.

2. Plugin:

In order to facilitate the control of the image, also wrote a few additional plug-ins, if the students in the use of a duplicate, please try to avoid;-

$.FN.F: Used to get the style values for jquery objects, such as width, height, left, top, and so on.
$.fn.loadbitmap: Used to preload a picture to get the correct phase element.
$.fn.scalebitmap: for scaling pictures ... The scaling ratio comes from the global variable $zoomvalue.
$.fn.dragndrop: My last plugin $.fn. The drags version is designed to implement the drag-and-drop of a DOM object within a particular element.

3. API:

The $.fn.bitmapcutter APIs include:

src (String):The path to the picture to be cropped (relative to the Program home directory), the default is empty, and must be
Renderto (String (Selector) |jquery Object):Bitmapcutter plug-in container, jquery object or selector, default to $ (document.body),
holdersize (Object):The size of the holder object, including the width and height two values, default to {width:300, height:400},
cuttersize (Object):Cutter Object Size (generates avatar size), including width and height two values, default to {width:70, height:70},
Zoomstep (Float):The rate of change per zoom, default is 0.2,
zoomin (Float):Enlarge the maximum ratio with the original, the default is 2.0,
zoomout (Float):The maximum ratio of the original image when shrinking, the default is 0.1,
Rotateangle (Int):Picture rollover angle, the desirable value is 90, 180,-90,-180, default is 90,
Movestep (Int):The translation pixel when the original is translated, the default is 100,
ongenerated (Function):The number of events triggered when the avatar is successfully generated, Bitmapcutter passes a parameter ' src ' to this method, representing the avatar path of the new cropping generation. The default value for this property is function (src) {}.
Lang (Object):ToolTip for each button in the functional area, Lang's API is:

zoomout (String):Zoom in, default value ' Zoom out ',
zoomin (String):Shrink, default value ' Zoom in ',
Original (String):Original size, default value ' Original size ',
clockwise (String): Rotate clockwise, default value ' clockwise rotation ({0} degrees) ', including {0} to be populated with rotateangle values when formatting.
counterclockwise (String):Rotate counterclockwise with the default value ' counterclockwise rotation ({0} degrees) ' and include {0} to populate with Rotateangle values when formatting.
Generate (String):Generate avatar, default value ' generate! ',
process (String):When generating avatar, the default value is ' Please wait, transaction is processing ... ',
Left (String):Zopping move, default value ' left ',
Right (String):Right translation, default value ' right-hand ',
Up (String):Move up, default value ' up ',
Down (String):Move down, default value ' down '

The API prototype is:

4. Development skills:

In order to facilitate the code management and function optimization, the function has been summed up, can be broadly divided into:

Zoom (zoom): Subdivide to enlarge and shrink,
Flip (rotate): Subdivide to clockwise and counterclockwise,
Move: fine divided into | right | |-left translation.

So directly write three "base class" (Concrete realization See source code):
Izoom (ZV): Provides picture magnification or zoom out, Zv for current zoom ratio,
Irotate (angle): Provides image rotation function, angle for current rotation angle,
Imove (direction): Provides the original translation function, direction for moving direction, including ' left ', ' up ', ' right ', ' down '.

So what you need now is to subdivide each function:

Here I use an object scissors to encapsulate these operations, use call to ' inherit ', and of course you can use the ' impersonate ' or ' prototype chain ' methods. This makes it easy to use eval and JSON when binding these methods:

Can't you see? then put on an HTML tree?

5. Answer yourself

Q: Why should the rotation effect be achieved on the server side?
A: In order to achieve popular and browser-compatible, so I gave up the filters and canvas.

Q:photoshop and other picture processing software in the crop is to achieve the inverse effect, why not achieve?
A: I want a program to take into account the UI when also consider efficiency, if the reverse phase, the Cutter object also need to built-in an IMG to synchronize with the thumbimg, then when the rotation of the image memory accumulation is very scary.

Q: What's the benefit of siverlight, compared to flash?
A: Well, I originally intended to use flash, but given the popularity of the problem (how much.) NET developer will as?, Jquery+httphandler is a good choice, open API, open source, I think far more than let everyone to change one. The FLA comes with a relaxed and enjoyable.

Q: So bad?
A: We all know that the browser's cache is a double-edged sword, in the bitmapcutter he is very annoying, in order to achieve the image rotation after the refresh, only for the IMG src add a stamp (random number?) time? whatever.), but this will bring an inevitable result-browser memory accumulation ( The threat has now been minimized;-), Amount ... @#$%

6. Note

GIF type pictures are not specially processed, so only get back the first frame processing, generate avatar format for PNG, if necessary, modify the source code.
The Jquery.bitmapcutter.js tail method is necessary for simulating C # String.Format.
Support keyboard operation, key control translation, +-control zoom Zoom out, do not like to delete from the source code.

7. A simple example in demo

Use a picture of c.c to intercept the avatar, set the Intercept box to a length of 120:120, the container is the ID container div, each rotation angle of 90, clockwise rotation function button prompts for ' clockwise rotation {0} degrees. '

Effect:

8. Source Package (more Test pictures):

/201109/yuanma/bitmapcutter_jb51.rar

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.