js:
<script type="text/javascript" src="${base}/template/cutimage/jquery-1.7.2.min.js"></script> <script type="text/javascript" src="${base}/template/cutimage/jquery.ajaxfileupload.js"></script> <link rel="stylesheet" type="text/css" href="${base}/template/cutimage/jquery-ui-1.css"/> <script type="text/javascript" src="${base}/template/cutimage/jquery-ui-1.js"></script> <link href="${base}/template/cutimage/imgareaselect-default.css" rel="stylesheet" type="text/css"/> <script src="${base}/template/cutimage/jquery.imgareaselect.pack.js" type="text/javascript"></script> <script type="text/javascript"> var imageName = ""; var x = 0; var y = 0; var w = 100; var h = 100; $(function(){ $('#cut_dialog_1').dialog({ autoOpen: false, modal: true, width: 500 }); }); function showDialog(){ $('#cut_dialog_1').dialog('open'); $('#cropzoom_container').attr("src","${base}/upload/image/"+imageName); return false; } $(function(){ $('#cropzoom_container').imgAreaSelect({aspectRatio:'1:1', handles:true, fadeSpeed:200, onSelectChange:preview, remove:false}); }); function imgUpload(){ var file=$("#cut_file"); var filePath = file.val(); if(file.val()==''){ alert("请选择要上传的文件!"); return; } var fileName = filePath.substring(filePath.lastIndexOf('\\')+1); $.ajaxFileUpload({ url:'file_upload!imageUpload.action', secureuri:false, fileElementId:'cut_file', dataType: 'json', success: function (data, status){ if(data.status == 'success') { $('#cropzoom_container').imgAreaSelect({aspectRatio:'1:1', handles:true, fadeSpeed:200, onSelectChange:preview, remove:false}); imageName = data.imgName; showDialog(); }else{ alert("图片上传错误!"); } } }); } function preview(img, selection){ var scaleX = 100 / selection.width; var scaleY = 100 / selection.height; $('#preview img').css({ width: Math.round(scaleX * 300), height: Math.round(scaleY * 300), marginLeft: -Math.round(scaleX * selection.x1), marginTop: -Math.round(scaleY * selection.y1) }); x = selection.x1; y = selection.y1; w = selection.width; h = selection.height; } function buildLogo(){ var src = $("#cropzoom_container").attr("src"); src = src.substring(src.lastIndexOf("/")+1); closeDialog(); $.ajax({ url : "file_upload!cutImage.action", data : {"src":src, "x":x, "y":y, "w":w, "h":h}, dataType : "json", async : false, success : function(data){ if(data.status = "success"){ $("#logoImage").attr("src", "../" + data.loginImageSrc); $("#logoUrl").val(data.loginImageSrc); } } }); } function closeDialog(){ $('#cut_dialog_1').dialog('close'); $('#cropzoom_container').imgAreaSelect({remove: true}); if(imageName != ""){ $.ajax({ url: "file_upload!deleteImage.action", data: {imageName: imageName}, dataType: "json", async: false, success: function(data){ } }); } } </script> <input type="hidden" value="/upload/image/defalult.jpg" name="logoUrl" id="logoUrl"/> <div style="border:1px solid #ccc; width:300px; padding:2px"> <div style="width:100px; height:100px; align:center; margin:0 auto;"> <img id="logoImage" name="logoImage" src="${base}/upload/image/defalult.jpg" style="width:100px; height:100px; align:center; margin:0 auto;"/> </div> <input id="cut_file" type="file" name="file" value="浏览" style="border:1px solid #ccc;"/> <input onclick="imgUpload()" type="button" value="上传" style="border:1px solid #ccc; float:right;"/> </div> <div id="cut_dialog_1" class="ui-dialog-content ui-widget-content" style="width: auto; min-height: 26px; height: 300;"> <div style="height:auto;overflow:hidden;position:relative;"> <img id="cropzoom_container" src="" style="width:466;height:auto;align:center"/> </div> <a href="javascript:buildLogo()">确定</a> <a href="javascript:closeDialog()">取消</a> </div>
java1:
package com.kpmobile.action.admin; import java.awt.image.BufferedImage; import java.io.File; import javax.annotation.Resource; import javax.imageio.ImageIO; import net.sf.json.JSONObject; import com.kpmobile.action.shop.BaseShopAction; import com.kpmobile.bean.ProductImage; import com.kpmobile.service.ProductImageService; import com.kpmobile.util.CommonUtil; import com.kpmobile.util.FileUploadUtil; import com.kpmobile.util.ImageUtil; public class FileUploadAction extends BaseShopAction{ private static final long serialVersionUID = 1L; private File[] file; private String fileName; @Resource private ProductImageService productImageService; //图片文件上传 public String imageUpload() throws Exception{ String newUrl = ""; if(file != null && file.length > 0){ newUrl = getRequest().getSession().getServletContext().getRealPath("/")+"upload\\image\\"; fileName = "temp0_" + CommonUtil.getUUID() + ".jpg"; FileUploadUtil.upload(file[0], newUrl, fileName); File file = new File(newUrl+fileName); BufferedImage bufferedImage = ImageIO.read(file); int srcWidth = bufferedImage.getWidth(); int srcHeight = bufferedImage.getHeight(); int width = 466; int maxHeight = 500; int height = width*srcHeight/srcWidth > maxHeight ? maxHeight : (width*srcHeight/srcWidth); ImageUtil.zoom2(bufferedImage, file, height, width); } JSONObject json = new JSONObject(); json.put("status", "success"); json.put("imgName", fileName); return ajaxJson(json.toString()); } //图片剪裁 public String cutImage() throws Exception{ String sFile = getRequest().getSession().getServletContext().getRealPath("/")+"upload\\image\\" + getParameter("src"); int x = Integer.parseInt(getParameter("x")); int y = Integer.parseInt(getParameter("y")); int width = Integer.parseInt(getParameter("w")); int height = Integer.parseInt(getParameter("h")); ProductImage logoImage = productImageService.buildLogoImg(new File(sFile), x, y, width, height); JSONObject json = new JSONObject(); json.put("status", "success"); json.put("loginImageSrc", logoImage.getLogoImg()); return ajaxJson(json.toString()); } //删除图片 public String deleteImage(){ //未实现 return null; } public File[] getFile() { return file; } public String getFileName() { return fileName; } public void setFile(File[] file) { this.file = file; } public void setFileName(String fileName) { this.fileName = fileName; } }
java2:
package com.kpmobile.util; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; public class FileUploadUtil { public static void upload(File file,String url,String fileName){ try { FileUtils.copyFile(file, new File(url, fileName)); } catch (IOException e) { e.printStackTrace(); } } }
java3:
package com.kpmobile.util; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.awt.image.CropImageFilter; import java.awt.image.FilteredImageSource; import java.awt.image.ImageFilter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; 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.kpmobile.bean.SystemConfig.WatermarkPosition; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder; public class ImageUtil { /** * 图片缩放(图片等比例缩放为指定大小,无填充) * * @param srcBufferedImage * 源图片 * @param destFile * 缩放后的图片文件 */ public static void zoom2(BufferedImage srcBufferedImage, File destFile, int destHeight, int destWidth) { try { int imgWidth = destWidth; int imgHeight = destHeight; int srcWidth = srcBufferedImage.getWidth(); int srcHeight = srcBufferedImage.getHeight(); if (srcHeight >= srcWidth) { imgWidth = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth)); } else { imgHeight = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight)); } BufferedImage destBufferedImage = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = destBufferedImage.createGraphics(); graphics2D.clearRect(0, 0, destWidth, destHeight); graphics2D.drawImage(srcBufferedImage.getScaledInstance(imgWidth, imgHeight, Image.SCALE_SMOOTH), (destWidth / 2) - (imgWidth / 2), (destHeight / 2) - (imgHeight / 2), null); graphics2D.dispose(); ImageIO.write(destBufferedImage, "JPEG", destFile); } catch (IOException e) { e.printStackTrace(); } } }
java4:
package com.kpmobile.service.impl; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import javax.imageio.ImageIO; import javax.imageio.ImageReadParam; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import org.apache.commons.io.FileUtils; import org.apache.struts2.ServletActionContext; import org.springframework.stereotype.Service; import com.kpmobile.bean.ProductImage; import com.kpmobile.bean.SystemConfig; import com.kpmobile.service.ProductImageService; import com.kpmobile.util.CommonUtil; import com.kpmobile.util.ImageUtil; import com.kpmobile.util.SystemConfigUtil; @Service public class ProductImageServiceImpl implements ProductImageService { public ProductImage buildLogoImg(File uploadImg, int x, int y, int width, int height) throws Exception{ FileInputStream fis = null; ImageInputStream iis = null; try{ fis = new FileInputStream(uploadImg); Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName("jpg"); ImageReader reader = it.next(); iis = ImageIO.createImageInputStream(fis); reader.setInput(iis, true); ImageReadParam param = reader.getDefaultReadParam(); Rectangle rect = new Rectangle(x, y, width, height); param.setSourceRegion(rect); BufferedImage bi = reader.read(0,param); String uuid = CommonUtil.getUUID(); String logoImgPath = SystemConfig.UPLOAD_IMAGE_DIR + "logo_" + uuid + "." + "jpg"; ProductImage productImage = new ProductImage(); productImage.setId(uuid); productImage.setLogoImg(logoImgPath); ImageIO.write(bi, "jpg", new File(ServletActionContext.getServletContext().getRealPath(logoImgPath))); return productImage; }catch(Exception e){ e.printStackTrace(); return null; }finally{ if(fis != null) fis.close(); if(iis != null) iis.close(); uploadImg.delete(); } } }
附:
传送门:http://www.cnblogs.com/mizzle/archive/2011/10/13/2209891.html
选项 |
描述 |
aspectRatio |
长宽比,以后在选择时候就会维持不变。 e.g. "4:3" |
autoHide |
如果设为true,那么在选择完后区域会消失。 Default:false |
classPrefix |
预先给插件元素的前缀(详见下面:5、元素与类) Default:imgareaselect |
disable |
如果设置成true,这个插件将不起作用(但是图像还是可见的) |
enable |
如果设置成true,这个插件又将重新起作用 |
fadeSpeed |
若设置成大于零的某个数,将"渐隐/渐现"这个插件 Default:true |
handles |
若设置成true,在改变大小的时候显示改变框(就是角点有些小"矩形") Default:false |
hide |
若设置成true,则隐藏选择框 |
imageHeight |
图像的真实高度(因为有可能被CSS缩放过了) |
imageWidth |
图像的真实宽度(因为有可能被CSS绽放过了) |
instance |
若设为true,imgAreaSelect()函数会返回一个对选择区域图像的一个引用,以便能够进一步使用API。(详见8、API方法) |
keys |
启用/关闭键盘支持(详见7、键盘支持) Default:false |
maxHeight |
限制选择框(以像素为单位),设置最大、最小的高度、宽度。 |
maxWidth |
|
minHeight |
|
minWidth |
|
movable |
设置是否支持选择框移动 Default:true |
parent |
指定此插件默认所附加到的父元素 Default:body |
persistent |
若设置成true,点击选择区域外将开始一个新的选项(换言之,是否让用户只能移动/缩放选择区域) Default:false |
remove |
若设置成true,则该插件将完全移除 |
resizable |
决定选择区域是否可以改变大小 Default:true |
resizeMargin |
当选择区域宽度超过多少像素时将启用"可改变大小"模式 |
show |
如果设置成true,选择区域将可见 |
x1 y1 |
初始化时选择框左上角的坐标 |
x2 y2 |
初始化时选择框右下角的坐标 |
zIndex |
设置此插件所作用元素的z-index的值,一般情况下,imgAreaSelect 总是可以自动计算出它的值,但是极少数情况下还是有必要设置的。 |
onInit |
当插件初始化时所调用的函数(详见6、回调函数) |
onSelectStart |
当开始选择时所调用的函数(详见6、回调函数) |
onSelectChange |
当改变选择区域时所调用的函数(详见6、回调函数) |
onSelectEnd |
当选择结束时所调用的函数(详见6、回调函数) |