Just completed an upload avatar module, hope pointing (including detailed code)

Source: Internet
Author: User

File APIto read local files directly. fileapi and jcrop are used to upload avatars.

  1 , HTML Part

<input id= "Demo" type= "file" name= "file" onchange= "Showpic ();" />

  2 , Fileapi Preview Picture

<script type= "Text/javascript" >

function Showpic () {

var file = $ (' #demo ') [0].files[0];

var reader = new FileReader ();

Reader.onload = function () {/////is triggered after successful loading. Reader.onloadend load success or failure will trigger

$ (' #avatar '). attr (' src ', reader.result);

}

Reader.readasdataurl (file);

}

  </script>

  3 , Jcrop capture a picture tool

<link rel= "stylesheet" href= "./jcrop/css/jquery. Jcrop.css "/>

<script src= "./jquery-1.8.3.min.js" type= "Text/javascript" ></script>

The project itself 1.11 a bit problematic, the project version is not supported, again in the following reference again 1.8.2 the previous version covered, I tried to be able to

<script type= "Text/javascript" src= "./jcrop/js/jquery. JCrop.min.js "></script>

<script type= "Text/javascript" >

var Jcrop_api;

function Showpic () {

var file = $ (' #demo ') [0].files[0];

var reader = new FileReader ();

Reader.onloadend = function () {

$ (' #avatar '). attr (' src ', reader.result);

}

Reader.readasdataurl (file);

var Jcrop_api = $. Jcrop ($ ("#avatar"), {//Initialize Jcrop

Aspectratio:1,//set to square

onchange:showcoords,//

Onselect:showcoords

});

}

function Showcoords (coords) {//preview crop effect, no detail written

Console.log (coords);//Information

}

</script>

  4 , image and interception data are sent back to the table.

The Jcrop getscalefactor () method can get the picture scale [w,h]. But what I've been getting is 1:1, not at all.

Back to the data to use two things, one is Formdata, one is XMLHttpRequest.

var formData = new FormData;

Formdata.append (' file ', $ (' #demo ') [0].files[0]);

Formdata.append (' x ', jcrop_api.tellscaled (). x);

Formdata.append (' Y ', jcrop_api.tellscaled (). y);

Formdata.append (' W ', Jcrop_api.tellscaled (). W);

Formdata.append (' H ', jcrop_api.tellscaled (). h);//above XYWH four values for trimming small plots

Formdata.append (' Showheight ', $ (' #avatar '). style.height);//The picture is uploaded to the background in the display height of the page to calculate the scale of the picture

XMLHTTP = new XMLHttpRequest ();

Xmlhttp.open ("POST", url,true);

Xmlhttp.send ();//is an Ajax

5. Background processing

Background spring receive, cut with BufferedImage

public void Setavatar (multipartfile file,integer x,integer y,integer w,integer h,integer showheight) {

try {

String suffix = file.getoriginalfilename (). Split (".") [File.getoriginalfilename (). Split ("."). LENGTH-1];

String Avatarpath = "d:\\file\\" +uuid.randomuuid (). toString (). ReplaceAll ("_", "") + "." +suffix;

BufferedImage bi = imageio.read (File.getinputstream ());

BigDecimal realheight = new BigDecimal (bi.getheight () + "");

BigDecimal ratio = Realheight.divide (New BigDecimal (showheight+ ""));

x = ratio.multiply (new BigDecimal (x)). Intvalue ();

y = ratio.multiply (new BigDecimal (y)). Intvalue ();

W = ratio.multiply (New BigDecimal (W)). Intvalue ();

h = ratio.multiply (new BigDecimal (h)). Intvalue ();

BufferedImage NEWBI = bi.getsubimage (x, Y, W, h);

Imageio.write (newbi, suffix, new File (Avatarpath));

/*

* Assign an accessible avatar file path to the user entity

*/

Return "Success";

} catch (Exception e) {

E.printstacktrace ();

return "error";

}

}

6. Problems encountered

After the page JS dynamically changes the SRC attribute of img, the width of IMG is sometimes not adaptive (sometimes, sometimes not). Causes the picture to be stretched, and the clipping result is inaccurate.

7. Attached Jcrop API

Parameters:

Name

Default value

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. Example: If the value is "test", then the style is added to the

BgColor

"Black"

Background color. Color keywords, HEX, RGB are available.

Bgopacity

0.6

Background transparency

Bgfade

False

Using 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

Method:

  

Name

Description

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].

There are some versions of jquery online. JCrop.min.js file does not contain this method, re-download a complete version

Just completed an upload avatar module, hope pointing (including detailed 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.