Jquery + httphandler for image cropping (applicable to forums and SNS)

Source: Internet
Author: User
Tags image flip

Preface:
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:

Bitmapcutter. Core is processed by the image server.Program, Class diagram:

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 container for the source image. 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 Div 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 ofCodeThere are many important points:

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:

In order to facilitate image control, several additional plug-ins are also compiled. If you have duplicate names in use, try to avoid

$. 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 },< br> 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 },< br> zoomstep (float): the ratio of each scaling change. The default value is 0.2,
zoomin (float): maximum ratio of the zoom in to the source image. The default value is 2.0.
zoomout (float ): the maximum ratio of the source image. The default value is 0.1.
rotateangle (INT): the image flip angle. The value can be 90,180, -90,-180, default value: 90.
movestep (INT): the pixel to be translated when the source image is translated. The default value is 100,
ongenerated (function): Number of events triggered when an avatar is successfully generated. bitmapcutter passes a parameter 'src' to this method ', specifies the path of the newly cropped avatar. the default value of this attribute is function (SRC) {},
Lang (object): tooltip of each button in the function area, and 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 DIV whose ID is container, and 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 ):
Google Code

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.