功能需求 “在上传照片的时候能进行裁剪”

Jcrop是一个jQuery插件,它能为你的WEB应用程序快速简单地提供图片裁剪的功能。Jcrop官网,以下是Jcrop的一些特性:

  • 对所有图片均unobtrusively(无侵入的,保持DOM简洁)
  • 支持宽高比例锁定
  • 支持 minSize / maxSize设置
  • 支持改变选区或移 动选区时的回调(Callback)
  • 支持用键盘微调选区
  • 通过API创建互 动,比如动画效果
  • 支持CSS样式

Jcrop使用

引入插件

<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/jquery.Jcrop.js"></script>  

引入Jcrop的CSS样式

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

例如想要实现如下效果,效果图:

html:基本结构

 <%-- 裁剪图片布局 --%>  <div class="jcrop_warpper"><div id="crop_image">  <div id="crop_image_top">  <h4>编辑图片</h4>  </div>  <div id="crop_image_content">  <img src="" alt="" id="JcropImage">  <!-- 预览 -->  <div id="preview-pane">  <div class="preview-container">  <img src="" alt="" id="JcropPreviewImage">  </div>  </div>  </div>  <div id="crop_image_bottom">  <input class="btn" type="button" value="取消">  <input id="submitBtn" class="btn cut" type="button" value="确定">  </div>  </div>  </div>    <!-- 上传图片表单 -->  <form id="uploadForm" action="">  <div id="uploadImage">  ![](images/test.jpg)  <a href="javascript:;" class="addImage">  <span>上传图片</span>  <input id="imgFile" type="file" name="imgFile">  </a>  </div>  </form>  

js:当点击上传图片时,弹出图片选择框,选择图片之后会替换掉裁剪框内容。这里利用change方法,监听imgFile改变事件。

var width;  // 裁剪框的宽度
var height; // 裁剪框的高度
var x;      // 裁剪框的起点x
var y;      // 裁剪框的起点y
var jcrop_api;
var xsize = $('#preview-pane .preview-container').width();  // 获取预览窗格相关信息
var ysize = $('#preview-pane .preview-container').height();
var $pimg = $('#preview-pane .preview-container img');
var $preview = $('#preview-pane');
var boundx;
var boundy;$('#imgFile').change(function(event) {// 根据这个 <input> 获取文件的 HTML5 js对象  var files = event.target.files, file;if (files && files.length > 0) {// 获取目前上传的文件 file = files[0];// Judge file typevar fileName = file.name;var fileType = fileName.substr(fileName.lastIndexOf(".")).toUpperCase();if (fileType != ".BMP" && fileType != ".PNG" && fileType != ".JPG" && fileType != ".JPEG") {alert("please select image!");return false;}// 获取window的 URL工具  var URL = window.URL || window.webkitURL;// 通过 file生成目标 url  var imgURL = URL.createObjectURL(file);if (jcrop_api) {jcrop_api.destroy();}$('#JcropImage').attr('src', imgURL);$('#JcropPreviewImage').attr('src', imgURL);$('#JcropImage').Jcrop({setSelect: [ 0, 0, 2000, 2000 ],allowResize: true,allowSelect: false,onChange : updatePreview,onSelect : updatePreview,aspectRatio : xsize / ysize,boxWidth: 348,boxHeight: 324}, function() {// 使用API来获得真实的图像大小var bounds = this.getBounds();boundx = bounds[0];boundy = bounds[1];jcrop_api = this;// 预览进入jcrop容器css定位 $preview.appendTo(jcrop_api.ui.holder);updatePreview();});}
});function updatePreview(c) {var jcropImage = $('#JcropImage').attr('src');var jcropPreviewImage = $('#JcropPreviewImage').attr('src');if (jcropImage != jcropPreviewImage) {$('#JcropPreviewImage').attr('src', jcropImage);$('#JcropPreviewImage').css('width', xsize);$('#JcropPreviewImage').css('height', '');}if (c != undefined){if (parseInt(c.w) > 0) {var rx = xsize / c.w;var ry = ysize / c.h;$pimg.css({width : Math.round(rx * boundx) + 'px',height : Math.round(ry * boundy) + 'px',marginLeft : '-' + Math.round(rx * c.x) + 'px',marginTop : '-' + Math.round(ry * c.y) + 'px'});}x = Math.round(c.x);y = Math.round(c.y);width = Math.round(c.w);height = Math.round(c.h);}
};$('.cut').off('click').on('click', function() {var formData = new FormData();formData.append(nameSpace + 'file', $('#imgFile')[0].files[0]);formData.append(nameSpace + 'startX', x);formData.append(nameSpace + 'startY', y);formData.append(nameSpace + 'width', width);formData.append(nameSpace + 'height', height);formData.append(nameSpace + 'realW', Math.round(boundx));formData.append(nameSpace + 'realH', Math.round(boundy));$.ajax({// send ajax request})
});
.dialog-mask {position: fixed;top: 0;right: 0;bottom: 0;left: 0;overflow: hidden;outline: 0;-webkit-overflow-scrolling: touch;background-color: rgb(0, 0, 0);filter: alpha(opacity=60);background-color: rgba(0, 0, 0, 0.6);z-index: 1001;width: 150%;display: none;
}.jcrop_warpper {width: 148%;height: 148%;position: fixed;z-index: 1002;left: 14%;top: 18%;padding: 0% 77% 0% 0%;display: none;
}#crop_image {float: left;width: 100%;background-color: #333;user-select: none;border: 1px solid #DEDEDE;-webkit-border-radius: 6px;-moz-border-radius: 6px;border-radius: 6px;-webkit-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);-moz-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);display: none;
}#crop_image_top,#crop_image_bottom {float: left;width: 100%;padding: 2%;background-color: white;
}#crop_image_bottom {text-align: right;
}#crop_image_bottom input {height: 30px;padding: 5px 15px;border-radius: 3px;border: none;margin-left: 20px;outline: none;
}#submitBtn {color: white;cursor: pointer;
}#crop_image_top h4 {margin: 0;padding: 0;font-weight: normal;
}#crop_image_content {float: left;position: relative;text-align: center;width: 100%;margin: 3%;min-height: 200px;max-height: 400px;
}.jcrop-holder {left: 23px;
}.jcrop-holder #preview-pane {display: block;position: absolute;z-index: 2000;top: 0px;left: 475px;padding: 6px;border: 1px rgba(0, 0, 0, .4) solid;background-color: white;-webkit-border-radius: 6px;-moz-border-radius: 6px;border-radius: 6px;-webkit-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);-moz-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
}/* The Javascript code will set the aspect ratio of the croparea based on the size of the thumbnail preview,specified here */
#preview-pane .preview-container {width: 348px;height: 162px;overflow: hidden;
}#JcropPreviewImage {width: 348px;
}

后台:

public void cutImageAndImport(ResourceRequest request, ResourceResponse response) {//获取前台参数int x = *******;int y = *******;int width = *******;int height = *******;int realW = *******;int realH = *******;//将file对象转换成流InputStream in = uploadPortletRequest.getFileAsStream(Constants.FILE);//存储路径处理String fileName = this.postProcessFileNameBeforeSave(origionFileName);String filePath = httpServletRequest.getSession().getServletContext().getRealPath(Constants.UPLOAD_PATH);String imagePath = filePath + StringPool.FORWARD_SLASH + fileName;File file =new File(filePath);if (!file.exists() && !file.isDirectory()) {file.mkdir();}File imageFile = new File(filePath, fileName);//Cut imageBoolean cutResult = OperateImageUtil.cutImage(imagePath, in, x, y, width, height, realW, realH);
}//图片裁剪类
public class OperateImageUtil {public static Boolean cutImage(String imagePath, InputStream in, int x, int y, int width, int height, int realW, int realH) {Boolean result = Boolean.TRUE;try {BufferedImage bi = ImageIO.read(in);// Get image zoom out ratio, and calculate real cut size// 解决使用Jcrop剪切图片因图片太大导致精准度丢失的解决办法Double fileX = bi.getWidth() / (double) realW;Double fileY = bi.getHeight() / (double) realH;int newX =(int) (x * fileX);int newY =(int) (y * fileY);int newW =(int) (width * fileX);int newH =(int) (height * fileY);int srcWidth = bi.getWidth();int srcHeight = bi.getHeight();if (srcWidth > 0 && srcHeight > 0) {Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);ImageFilter cropFilter = new CropImageFilter(newX, newY, newW, newH);Image img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));BufferedImage tag = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_RGB);Graphics g = tag.getGraphics();g.drawImage(img, 0, 0, newW, newH, null);g.dispose();ImageIO.write(tag, Constants.PNG, new File(imagePath));}} catch (Exception e) {result = Boolean.FALSE;}return result;}
}//如果要下载裁剪后的图片
public void downloadImage(ResourceRequest request, ResourceResponse response) {// Step1: Gets parameters.String fileName = ParamUtil.getString(request, "fileName", StringPool.BLANK);HttpServletRequest httpServletRequest = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(request));HttpServletResponse httpServletResponse = PortalUtil.getHttpServletResponse(response);//设置http response header "Content-Disposition" 为 attachment,浏览器会自动下载文件httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + fileName);String filePath = httpServletRequest.getSession().getServletContext().getRealPath("/upload");String imagePath = filePath + "/" + fileName;File file = new File(imagePath);// 使用Outputstream返回文件流byte[] buff = new byte[1024];BufferedInputStream bis = null;OutputStream os = null;try {os = httpServletResponse.getOutputStream();bis = new BufferedInputStream(new FileInputStream(file));int i = 0;while ((i = bis.read(buff)) != -1) {os.write(buff, 0, i);os.flush();}} catch (IOException e) {e.printStackTrace();} finally {try {bis.close();} catch (IOException e) {e.printStackTrace();}}
}

Jcrop实现图片裁剪相关推荐

  1. jcrop java_SpringMVC结合Jcrop实现图片裁剪

    本文实例为大家分享了SpringMVC结合Jcrop实现图片裁剪的具体代码,供大家参考,具体内容如下 一.jsp页面: method="post" enctype="mu ...

  2. 使用JCrop进行图片裁剪,裁剪js说明,裁剪预览,裁剪上传,裁剪设计的图片处理的工具类和代码

     1.要想制作图片裁剪功能,可以使用网上的裁剪工具JCrop,网址是:https://github.com/tapmodo/Jcrop/ 案例效果如下: 2.引入JCrop的js代码,具体要引入那 ...

  3. springboot+Jcrop实现图片裁剪(模仿邮箱注册上传头像)

    1.pom配置 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="htt ...

  4. 图片裁剪入门Jcrop

    互联网时代,越来越丰富多彩.当然,这离不开网络上各种各样的图片.然而,这也提高了我们对图片处理的要求.像百度.腾讯这样的数量级的处理,如果对图片的上传没有一些优化,那么每年多花费五六十台服务器.额外话 ...

  5. jQuery 图片裁剪插件 Jcrop

    Jcrop是一个jQuery图片裁剪插件,它能为你的WEB应用程序快速简单地提供图片裁剪的功能.特点如下: 对所有图片均unobtrusively(无侵入的,保持DOM简洁) 支持宽高比例锁定 支持 ...

  6. php ci 处理图片 裁剪,jquery.form + Jcrop + CI框架实现图片裁剪上传

    功能: 1.通过jquery.form上传图片,并按一定比例显示预览图. 2.通过Jcrop裁剪图片,并显示裁剪预览图 3.通过CI的图像处理类保存剪切后图片 问题: 1.通过jquery.form来 ...

  7. 图片裁剪插件Jcrop.js的使用

    中文API文档地址:http://code.ciaoca.com/jquery/jcrop/ 简单使用裁剪: <!DOCTYPE html> <html lang="en& ...

  8. Java实现图片裁剪预览功能

    Java实现图片裁剪预览功能 在项目中,我们需要做些类似头像上传,图片裁剪的功能,ok看下面文章! 需要插件:jQuery Jcrop 后端代码: package org.csg.upload;imp ...

  9. 图片裁剪的js有哪些(整理)

    图片裁剪的js有哪些(整理) 一.总结 一句话总结:如果用了amaze框架就去amaze框架的插件库里面找图片裁剪插件,如果没用,jcrop和cropper都不错. 1.amazeui的插件库中有很多 ...

  10. Java+Javascript图片裁剪简单封装

    在做项目的过程中,有很多时候前端的图片会出现拉伸现象,所以在上传图片的时候,图片裁剪是必不可少的.所以有了封装一个图片裁剪工具的念头,下面是实现步骤: 1.首先选择一个前台裁剪工具,我这里使用的是Jc ...

最新文章

  1. PL/SQL12中文版
  2. webpack入坑指南
  3. ipad Simulator 的home 键的调用
  4. python 面对对象思维导图_Python面向对象思维导图
  5. 笨办法学 Python · 续 练习 50:`vi`
  6. 二叉搜索树的2层结点统计_植树节,程序猿种的那些树
  7. 西瓜书+实战+吴恩达机器学习(十三)监督学习之随机森林 Random Forest
  8. MATLAB关于Mesh的相关命令
  9. php 按引用传递的使用
  10. python控制雷电模拟器
  11. 一次简单的PC游戏汉化
  12. 个人记录—— The bean ‘xxx.FeignClientSpecification‘ could not be registered ...
  13. Unity - IL2CPP报错
  14. Linux SCSI设备容量打印代码分析
  15. Android平板能装fydeos,在 FydeOS 中如何安装安卓应用 - FydeOS 帮助手册
  16. 《一个投资家的20年》读书笔记
  17. MySQL(更新中)
  18. 小程序使用场景展示-小程序开发
  19. linux环境下常用的打包、压缩、解压命令(tar、gzip、bzip2、zip)
  20. python枪战项目计划书_用python分析了20万场吃鸡数据

热门文章

  1. os.system和os.popen函数的区别
  2. java lucene 站内搜索_完整的站内搜索Demo(Lucene.Net+盘古分词)
  3. ADS1115的四通道使用
  4. edge下载网络问题无法下载
  5. 移动网络通信技术【移动电话网络介绍】
  6. 国际象棋渲染测试软件,国际象棋与Cinebench渲染
  7. 九章量子计算机 知乎,量子计算机《九章》问世 知乎微博消息: 北京时间 12 月 4 日凌晨 3 点,一篇重要文章以 First Releas... - 雪球...
  8. 51单片机最小系统板制作
  9. Android Studio主菜单(Main Menu)消失后,恢复显示
  10. html css blockquote,css之blockquote美化