您的位置:首页 > Web前端 > JQuery

jquery 上传头像预览

2012-11-22 15:52 459 查看
参考:http://odyniec.net/projects/imgareaselect/

前端:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<link rel="stylesheet" type="text/css" href="${basePath}css/imgcss/imgareaselect-default.css" />

<script src="${basePath}js/jquery-1.7.1.min.js" ></script>

<script src="${basePath}js/jquery.form.js" ></script>

<script src="${basePath}js/jquery.imgareaselect.pack.js" type="text/javascript"></script>

<script type="text/javascript">

var realImgWidth = 0;

var realImgHeight = 0;

var scissorX = 50;

var scissorY = 50;



function scissor(){

var imagePath = document.getElementById("imagePath").value;

var tt = document.getElementById("imagePath");

var aa = $("#imagePath");

if(imagePath=="" || imagePath==null){

alert("<bean:message key='label.uploadPhoto' />!");

return false;

}else{

//先把图片上传到服务器

$("#headForm").ajaxSubmit({

type: "POST",

url: "${basePath}myzonePar.do?method=uploadPic¶m="+Math.random(),

//data: "classId="+classId,

dataType: "json",

success: function(result){

$("#imgtarget").attr("src","${basePath}upload/"+ result.picName);

$("#ximg").attr("src", "${basePath}upload/"+ result.picName);

$("#qietu").show();



document.getElementById("uploadImg").value = result.picName;

setTimeout(function(){

realImgWidth = $("#imgtarget").width();

realImgHeight = $("#imgtarget").height();

var ias = $('#imgtarget').imgAreaSelect({ instance: true });



if(parseInt(realImgWidth)<50){

scissorX = parseInt(realImgWidth);

}

if(parseInt(realImgHeight)<50){

scissorY = parseInt(realImgHeight);

}

ias.setSelection(0, 0, scissorX, scissorY, true);

ias.setOptions({ show: true });

ias.update();

$('.imgareaselect-selection').show();

},1000);



}

});

}

}



function preview(img, selection) {

if (!selection.width || !selection.height)

return;



var scaleX = scissorX / selection.width;

var scaleY = scissorY / selection.height;

$('#preview img').css({

width: Math.round(scaleX* parseInt(realImgWidth) ),

height: Math.round(scaleY * parseInt(realImgHeight) ),

marginLeft: -Math.round(scaleX * selection.x1),

marginTop: -Math.round(scaleY * selection.y1)

});

$('#x1').val(selection.x1);

$('#y1').val(selection.y1);

$('#x2').val(selection.x2);

$('#y2').val(selection.y2);

$('#scaleWidth').val(selection.width);

$('#scaleHeight').val(selection.height);

}

$(function () {

$('#imgtarget').imgAreaSelect({ aspectRatio: '1:1', handles: true,show:true,

fadeSpeed: 200, maxHeight:50, maxWidth:50, minHeight:50, minWidth:50, onSelectChange: preview, onInit:preview });

});

</script>

</head>

<body>

<form id="headForm" name="headForm" method="post" enctype="multipart/form-data" action="${basePath}myzonePar.do?method=toUpdateHeadImage">

<div class="shangchuan">

<div class="shangchuan_left">

<div >

<c:choose>

<c:when test="${!empty headImage}">

<img src="${basePath}showImage.do?uuid=${uuid}" width="50" height="50" /><br/>

</c:when>

<c:otherwise>

<img src="${basePath}jsp/parents/image/qshead.jpg" width="50" height="50" /><br/>

</c:otherwise>

</c:choose>

</div>

</div>

<div class="shangchuan_right">

<input id="imagePath" name="file" size="30" style=" margin-top:20px; height:25px;" type="file" onChange="scissor()"/>

<div style="width:150px; float:left; padding-top:5px;"></div>

<div style="float:left; margin-left:99px; width:190px;"><img src="${basePath}/jsp/parents/<bean:message key='label.image' />/tianjia01.png" id="updateHeadImg" name="updateHeadImg" onClick="updateImgFun()"style="margin-top:5px; float:right;
cursor:pointer;"/></div>

</div>

</div>

<div id="qietu" style="height: 150px; margin:2px 0 0 100px; display:none;">

<div style="width:150px; height: 150px; float:left; ">

<div id="imgg" style=" border:1px solid green; float:left; overflow: hidden;">

<img id="imgtarget" src="" />

</div>

</div>

<div style="width:20px; height:150px; border:0px; float:left;"></div>

<div class="frame" style="margin:10px 10px 0 30px; width: 50px; height: 150px; float:left;">

<div id="preview" style="width: 50px; height: 50px; overflow: hidden;">

<img id="ximg" name="ximg" src="" >

</div>

</div>

<input type="text" id="uploadImg" name="uploadImg" value="" style="display:none;"/>

<table style="margin-top: 1em; height:150px; display:none;">

<thead>

<tr>

<th colspan="2" style="font-size: 110%; font-weight: bold; text-align: left; padding-left: 0.1em;">

Coordinates

</th>

<th colspan="2" style="font-size: 110%; font-weight: bold; text-align: left; padding-left: 0.1em;">

Dimensions

</th>

</tr>

</thead>

<tbody>

<tr>

<td style="width:20px;"><b>X<sub>1</sub>:</b></td>

<td><input id="x1" name="x1" value="0" type="text" size="5" readonly="true"></td>

<td style="width:20px;"><b>Width:</b></td>

<td><input value="-" id="scaleWidth" name="scaleWidth" type="text" size="5" readonly="true"></td>

</tr>

<tr>

<td><b>Y<sub>1</sub>:</b></td>

<td><input id="y1" name="y1" value="0" type="text" size="5" readonly="true"></td>

<td><b>Height:</b></td>

<td><input id="scaleHeight" name="scaleHeight" value="-" type="text" size="5" readonly="true"></td>

</tr>

<tr>

<td><b>X<sub>2</sub>:</b></td>

<td><input id="x2" name="x2" value="50" type="text" size="5" readonly="true"></td>

<td></td>

<td></td>

</tr>

<tr>

<td><b>Y<sub>2</sub>:</b></td>

<td><input id="y2" name="y2" value="50" type="text" size="5" readonly="true"></td>

<td></td>

<td></td>

</tr>

</tbody>

</table>

</div>

</form>

</body>

</html>

后台:

public ActionForward uploadPic(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, IOException{

UploadFormBean uf =(UploadFormBean)form;

FormFile file = uf.getFile();

System.out.println(file.getFileSize());



if(file.getFileSize() > 0){

try {

InputStream stream = file.getInputStream();

String filePath = request.getRealPath("/")+"upload/";



SimpleDateFormat df=new SimpleDateFormat("yyyyMMddHHmmss");

String str=df.format(new Date());



filePath = filePath + str + file.getFileName();

OutputStream bos = new FileOutputStream(filePath);

int bytesRead = 0;

byte[] buffer = new byte[2*1024*1024];

while ((bytesRead = stream.read(buffer, 0, 2*1024*1024)) != -1) {

bos.write(buffer, 0, bytesRead);

bos.flush();

}

bos.close();

stream.close();

BufferedImage sourceImage = ImageIO.read(new File(filePath));

int height = sourceImage.getHeight();

int width = sourceImage.getWidth();

if(file.getFileSize() > 10*1024 || (width>50 && height>50)){ //大于10k进行压缩

//按比例压缩

ImageUtil.scaleImage(150, 150*height/width, filePath,filePath);

sourceImage = ImageIO.read(new File(filePath));

width = sourceImage.getWidth();

height = sourceImage.getHeight();

if(height>150){

ImageUtil.scaleImage(150*150/height, 150, filePath,filePath);

}

}

JSONObject obj = new JSONObject();

String picName = str+file.getFileName();

obj.put("picName", picName);

PrintWriter out = response.getWriter();

out.print(obj);

out.close();



}catch(Exception e){

e.printStackTrace();

}

}

return null;

}



public ActionForward updateHeadImage(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, IOException{



UploadFormBean uf =(UploadFormBean)form;

FormFile file = uf.getFile();

Hashtable hashTable = uf.getMultipartRequestHandler().getTextElements();

System.out.println(hashTable);

String x11 = ((String[])hashTable.get("x1"))[0];

String x12 = ((String[])hashTable.get("x2"))[0];

String y11 = ((String[])hashTable.get("y1"))[0];

String y12 = ((String[])hashTable.get("y2"))[0];

String width = ((String[])hashTable.get("scaleWidth"))[0];

String height = ((String[])hashTable.get("scaleHeight"))[0];

String imageName = ((String[])hashTable.get("uploadImg"))[0];



System.out.println("imageName:"+imageName);



Integer x1 = Integer.parseInt(x11);

Integer x2 = Integer.parseInt(x12);

Integer y1 = Integer.parseInt(y11);

Integer y2 = Integer.parseInt(y12);

//Integer scaleWidth = Integer.parseInt(width);

//Integer scaleHeight = Integer.parseInt(height);

Integer scaleWidth = 50;

Integer scaleHeight = 50;



System.out.println("x1:"+x1+", x2:"+x2+", y1:"+y1+", y2:"+y2+", scaleWidth:"+scaleWidth+", scaleHeight:"+scaleHeight);



try{

SimpleDateFormat df=new SimpleDateFormat("yyyyMMddHHmmss");

String str=df.format(new Date());

String filePath = request.getRealPath("/")+"upload/";

String savePath = filePath + str + file.getFileName();



String originPath = request.getRealPath("/")+"upload/"+imageName;

System.out.println("originPath:"+originPath);

System.out.println("savePath:"+savePath);



if(x1 != null && x2 != null && y1 != null && y2 != null) {

//按尺寸裁剪图片

ImageUtil.scissor(x1, x2, y1, y2, originPath, savePath);

}



File scissorFile = new File(savePath); //读取裁剪后的图片

System.out.println("scissorFile.length():"+scissorFile.length());

if (scissorFile.length()>10*1024) { //如果裁剪后的图片大于10k进行压缩

//按比例压缩图片

ImageUtil.scaleImage(scaleWidth, scaleHeight, savePath,savePath);

}



FileInputStream in = new FileInputStream(savePath); //读取裁剪后的图片

//InputStream in = file.getInputStream();

ByteArrayOutputStream outStream = new ByteArrayOutputStream();

byte[] data = new byte[4096];

int count = -1;

while((count = in.read(data,0,4096)) != -1){

outStream.write(data, 0, count);

}

data = null;

outStream.toByteArray();



BASE64Encoder encoder = new BASE64Encoder();

String path = encoder.encode(outStream.toByteArray());



String token = (String) request.getSession().getAttribute("token");

IbssUser ibssUser = IbssUtils.getIbssUser(token);

ibssUser.setHeadImage(path);



String rtnCode = IbssUtils.updateHeadImage(token, ibssUser);

return null;

}



ImageUtil 类:提供压缩和裁剪图片的方法:

import java.awt.Rectangle;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.util.Iterator;

import javax.imageio.ImageIO;

import javax.imageio.ImageReadParam;

import javax.imageio.ImageReader;

import javax.imageio.stream.ImageInputStream;

import com.mortennobel.imagescaling.ResampleOp;

/**

* 图片处理工具类

*

*/

public class ImageUtil {



/**

* 根据传入的图片坐标进行图片截取

*

* @param x1 X起点坐标

* @param x2 X终点坐标

* @param y1 Y起点坐标

* @param y2 Y终点坐标

* @param originPath 原始图片的存放路径

* @param savePath 截取后图片的存储路径

* @throws IOException

*/

public static void scissor(int x1, int x2, int y1, int y2,

String originPath, String savePath) throws IOException {

ImageInputStream iis = null;

FileInputStream is = null;

try {

// 读取图片文件

is = new FileInputStream(originPath);



/*

* 返回包含所有当前已注册 ImageReader 的 Iterator,

* 这些 ImageReader 声称能够解码指定格式。

* 参数:formatName - 包含非正式格式名称 .(例如 "jpeg" 或 "tiff")等 。

*/

Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(getExtention(originPath)

.toLowerCase());

ImageReader reader = it.next();

// 获取图片流

iis = ImageIO.createImageInputStream(is);



/*

* iis:读取源.true:只向前搜索,将它标记为 ‘只向前搜索’。

* 此设置意味着包含在输入源中的图像将只按顺序读取,可能允许

* reader 避免缓存包含与以前已经读取的图像关联的数据的那些输入部分。

*/

reader.setInput(iis, true);



/*

* 描述如何对流进行解码的类,用于指定如何在输入时从 Java Image I/O

* 框架的上下文中的流转换一幅图像或一组图像。用于特定图像格式的插件

* 将从其 ImageReader 实现的

* getDefaultReadParam方法中返回 ImageReadParam 的实例。

*/

ImageReadParam param = reader.getDefaultReadParam();



/*

* 图片裁剪区域。Rectangle 指定了坐标空间中的一个区域,通过 Rectangle 对象

* 的左上顶点的坐标(x,y)、宽度和高度可以定义这个区域。

*/

Rectangle rect = new Rectangle(x1, y1, x2 - x1, y2 - y1);



// 提供一个 BufferedImage,将其用作解码像素数据的目标。

param.setSourceRegion(rect);



/*

* 使用所提供的 ImageReadParam 读取通过索引 imageIndex 指定的对象,并将 它作为一个完整的

* BufferedImage 返回。

*/

BufferedImage bi = reader.read(0, param);



// 保存新图片

ImageIO.write(bi, getExtention(originPath).toLowerCase(), new File(

savePath));

}catch(Exception e){

e.printStackTrace();

} finally {

if (is != null)

is.close();

if (iis != null)

iis.close();

}

}



/**

*

* 缩放图片

*

* @param width 宽

* @param height 高

* @param originPath 原始路径

* @param savePath 保存路径

* @throws IOException

*/

public static void scaleImage(int width, int height, String originPath,

String savePath) throws IOException {



BufferedImage sourceImage = readImage(originPath);

ResampleOp resampleOp = new ResampleOp(width, height);

BufferedImage rescaledTomato = resampleOp.filter(sourceImage, null);

ImageIO.write(rescaledTomato, getExtention(originPath).toLowerCase(),

new File(savePath));

}



private static BufferedImage readImage(String imagePath) throws IOException {

return readImage(new File(imagePath));

}



private static BufferedImage readImage(File image) throws IOException {

return ImageIO.read(image);

}



/**

* 功能:提取文件名的后缀

*

* @param fileName

* @return

*/

private static String getExtention(String fileName) {

int pos = fileName.lastIndexOf(".");

return fileName.substring(pos + 1);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: