Code for image cropping Based on jQuery + HttpHandler (applicable to forums and SNS) _ jquery-js tutorial

Source: Internet
Author: User
Tags image flip
Last time I sent several jQuery plug-ins and some experiences, many garden friends (maybe on their own) sent emails hoping to provide more source code, this time, a student wanted to upload an image cropping function on his jar to generate an avatar, so he helped write such a plug-in. maybe a lot of garden friends can use it, so they will send it together.

Body:
The solution is as follows:

Here, BitmapCutter. Core is the server-side processing program of the image, and the class diagram is:

For more information, see the source code notes:

Cutter is the cropping object used to store data submitted by the client through AJAX.

Helper is an image processing class, including RotateImage () and GenerateBitmap ()).

Callback is a server-side image processing class. It uses Cutter to encapsulate the data submitted by the client AJAX, and then calls the methods in Helper to complete image processing.

BitmapScissors is an HttpHandler that calls the method in Callback using the 'Action' returned by the client:


Note: reflection is used to dynamically call the method in Callback based on the 'Action' value. If you are not used to it or think it is inappropriate, change it yourself...

The Url submitted by the client AJAX is "scissors. axd ", which is actually a BitmapScissors class (if you have modified the server-side processing program, go to the Web. httpHandler node configuration in config). In this example:

OK. The following describes the implementation of the $. fn. bitmapcutter plug-in:

Let's take a look at the above picture and mark the Dom object in bitmapcutter. Well, there are a lot of fans who like the big wood. Let's take a look at Zhang Luang:

Note:

Holder is the source image carrying container. When the source image is too large, only the part can be displayed. You can view the image of the area not displayed through translation. holder is p and set position to relative, in this way, when the position style of the source image img (same as the img object) is absolute, you can control its left and top values to display the image in translation. Note that the overflow of holder must be set to hidden, in this way, the img will be wrapped in the holder, and the img beyond the holder boundary will be hidden.

The cutter is the screenshot box. You can drag it to select the desired screenshot area. The drag area is in the holder container and the thumbnail is generated in thumbimg (Same principle as holder + img.

Opts-function area provides all available function buttons, including: Zoom in, zoom out, left shift, right shift, up shift, down move, restore, left rotate, right rotate.

Info-image Prime, used to display the aspect ratio of the image to be captured.

Principle:

It should be easy to see if you are familiar with css, and use the flexibility of relative positioning and js to control css.

Plugin description:

Because there are many plug-ins in the code, I will focus on it here:

1. Global variables:

Since some data and jQuery objects are frequently used throughout the cropping process, a global variable is defined for storage.

$ OriginalSize: the prime of the source image. It is obtained when the source image is loaded for the first time and cannot be changed. It mainly provides a pair of basic data (long and wide) for amplification, downgrading, and restoration ).
$ ZoomValue: Current scaling ratio, which is synchronized when zoomValue is zoomed in or out.
$ Thumbimg: Specifies the jQuery object for cropping area thumbnails. It is assigned a value when the dom is created.
$ Img: jQuery object of the source image, which is obtained when the dom is created.
$ Cutter: crop area, which is also obtained when the dom is created.

2. Plug-ins:

To facilitate image control, several additional plug-ins have also been compiled. If you have a duplicate name in use, try to avoid it ;-)

$. Fn. f: used to obtain the style values of jQuery objects, such as width, height, left, and top.
$. Fn. loadBitmap: Used to pre-load an image to obtain the correct prime element.
$. Fn. scaleBitmap: Used to scale an image... the scaling ratio comes from the global variable $ zoomValue.
$. Fn. dragnddrop: the custom version of my last plug-in $. fn. Drags is mainly used to drag a dom object into a specific element.

3. API:

$. Fn. bitmapCutter APIs include:

Src (String ):The path of the image to be cropped (relative to the main directory of the Program). The default value is null. required,
RenderTo (String (Selector) | jQuery Object ):BitmapCutter plug-in container, jQuery object or selector. The default value is $ (document. body ),
HolderSize (Object ):The size of the holder object, including the width and height values. The default value is {width: 300, height: 400 },
CutterSize (Object ):The size of the cutter object (the size of the generated Avatar), including the width and height values. The default value is {width: 70, height: 70 },
ZoomStep (Float ):The ratio of each scaling is changed. The default value is 0.2,
ZoomIn (Float ):The maximum ratio of the image to the source image. The default value is 2.0,
ZoomOut (Float ):The default value is 0.1,
RotateAngle (Int ):Image flip angle; optional values: 90,180,-90,-180; default value: 90,
MoveStep (Int ):The number of translated pixels when the source image is translated. The default value is 100,
OnGenerated (Function ):Number of triggered events when an avatar is successfully generated. bitmapCutter sends a parameter 'src' to indicate the path of the newly cropped avatar. The default value of this attribute is function (src ){},
Lang (Object ):Tooltip for each button in the function area. The lang API is:

Zoomout (String ):Zoom in. The default value is 'zoom out ',
Zoomin (String ):Zoom out. The default value is 'zoom in ',
Original (String ):Original size, default value: 'original size ',
Clockwise (String): Clockwise rotation. The default value is 'clockwise rotation ({0} degrees) '. It must contain {0} so that the rotateAngle value can be used for formatting,
Counterclockwise (String ):Counter-clockwise rotation. The default value is 'counterclockwise rotation ({0} degrees) '. It must contain {0} to be filled with the rotateAngle value during formatting,
Generate (String ):Generate an Avatar. The default value is 'generate! ',
Process (String ):The prompt when the Avatar is generated. The default value is 'Please wait, transaction is processing ......',
Left (String ):Left translation, default value: 'left ',
Right (String ):Right translation; default value: 'right ',
Up (String ):Move Up, default value 'up ',
Down (String ):Move Down. The default value is "Down'

The API prototype is:

4. development skills:

To facilitate code management and function optimization, the functions are summarized:

Zoom: zoom in or out,
Turn (rotate): divided into clockwise and clockwise,
Move: subdivided into upper | right | Lower | left translation.

Therefore, write three 'base class' directly (for specific implementation, refer to the source code ):
Izoom (zv): provides the image zoom-in or zoom-out function. zv is the current zoom-in ratio,
Irotate (angle): provides the image rotation function. angle indicates the current rotation angle,
Imove (direction): provides the original image translation function. direction is the moving direction, including 'left', 'up', 'right', and 'drop '.

Now, you need to subscribe to the following functions:

Here I use an object scissors to encapsulate these operations and use call to 'inherited '. Of course, you can also use 'impersonation' or 'prototype chain' to implement these operations. in this way, you can easily use eval and json when binding these methods:

Can't you see it? So what about the Html tree?

5. Self-answer

Q: Why is rotation on the server side?
A: To achieve popularization and browser compatibility, I gave up the filter and Canvas.

Q: Why don't image processing software, such as Photoshop, implement reverse effects during cropping?
A: I think efficiency should be considered when A program takes into account both the UI. If the reverse phase is implemented, an img should also be built in the cutter object to synchronize with thumbimg, the memory accumulation is terrible when images are rotated.

Q: What are the advantages of Siverlight compared to Flash?
A: Well, I originally planned to use Flash, but considering the popularity issue (How many. Net developers would be ?), JQuery + HttpHandler is a good choice, with open APIs and open source code. I think it is far easier and more enjoyable to change one. fla.

Q: What are the disadvantages?
A: As we all know, browser cache is A double-edged sword. bitmapCutter is very annoying. In order to refresh the image after rotation, you can only add A stamp (random number? Time? Whatever...), but this will bring about an inevitable result-browser memory accumulation (which has already minimized this threat;-), amount ..! @ # $ %

6. Note

No special processing is performed on gif images. Therefore, only the first batch of images is retrieved and the image format is Png. If necessary, modify the source code.
The end method of jquery. bitmapcutter. js is to simulate c # string. format, required.
Supports keyboard operations, steering keys to control translation, +-to control zoom-in and zoom-out, and can be deleted from the source code.

7. Simple example in demo

Use a C. C to capture the Avatar, set the length and width of the screenshot box to 120:120, the container is the id of the container p, each rotation angle is 90, the prompt for the clockwise rotation function button is 'clockwise rotation {0} degree.'

Effect:

8. source code package (many test images ):

/201109/yuanma/BitmapCutter_jb51.rar
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.