JCrop+ajaxUpload 图像切割上传的实例代码


Posted in Javascript onJuly 20, 2016

先给大家展示下效果图:

JCrop+ajaxUpload 图像切割上传的实例代码

页面代码

里面用户的uuid是写死的test

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE>
<html lang="en">
<head>
<title>用户头像剪裁</title>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<link rel="stylesheet" href="resources/Jcrop/css/jquery.Jcrop.css">
<link rel="stylesheet" href="resources/css/photo.css">
<script src="resources/js/jquery.min.js"></script>
<script src="resources/Jcrop/js/jquery.Jcrop.js"></script>
<script src="resources/js/ajaxfileupload.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="span12">
<div class="jc-demo-box">
<div class="page-header">
<h1>头像剪裁</h1>
</div>
<img src="resources/img/test.jpg" id="target" />
<div id="preview-pane" >
<div class="preview-container">
<img src="resources/img/test.jpg" class="jcrop-preview"/>
</div >
<div style='float:left;display:inline;'>
<a class='btn_addPic' href="javascript:void(0);">
<span><EM>+</EM>添加图片</span> 
<input id="upload_image" type="file" name="upimage" accept="image/*" class = "filePrew"/>
</a>
</div>
<div style='float:right;display:inline;'>
<a class='btn_addPic' href="javascript:void(0);" onclick='submit()'>
<span>提交</span> 
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript">
var global_api = "";
var boundx ="";//页面图片宽度
var boundy ="";//页面图片高度
var tag = false;
$(function() {
// Create variables (in this scope) to hold the API and image size
//创建变量(在这个范围)的API和图像大小
var jcrop_api,
// Grab some information about the preview pane
//获取一些信息预览窗格
$preview = $('#preview-pane'),
$pcnt = $('#preview-pane .preview-container'),
$pimg = $('#preview-pane .preview-container img'),
xsize = $pcnt.width(),
ysize = $pcnt.height();
$('#target').Jcrop({
onChange: updatePreview,
onSelect: updatePreview,
aspectRatio: xsize / ysize
},function(){
// Use the API to get the real image size
//使用API来获得真实的图像大小
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
// Store the API in the jcrop_api variable
//jcrop_api变量中存储API
jcrop_api = this;
// Move the preview into the jcrop container for css positioning
//预览进入jcrop容器css定位
$preview.appendTo(jcrop_api.ui.holder);
});
function updatePreview(c)
{
if (parseInt(c.w) > 0)
global_api=c;
{
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'
});
}
};
//=======选择图片回显===============
$('#upload_image').change(function(event) {
// 根据这个 <input> 获取文件的 HTML5 js 对象
var files = event.target.files, file; 
if (files && files.length > 0) {
// 获取目前上传的文件
file = files[0];
// 下面是关键的关键,通过这个 file 对象生成一个可用的图像 URL
// 获取 window 的 URL 工具
var URL = window.URL || window.webkitURL;
// 通过 file 生成目标 url
var imgURL = URL.createObjectURL(file);
// 用这个 URL 产生一个 <img> 将其显示出来
$('.jcrop-holder img').attr('src', imgURL);
$('.preview-container img').attr('src', imgURL);
}
});
//=============是否选择了本地图片==================
$("#upload_image").change(function(){
tag=true;
});
});
//========================================================
//======图片保存===========
function submit(){
if(tag&&global_api != ""){
ajaxFileUpload();
}else{
alert('你是不是什么事情都没干?');
}
}
//ajax文件上传
function ajaxFileUpload() {
$.ajaxFileUpload({
url: 'uploadphoto', //用于文件上传的服务器端请求地址
secureuri: false, //一般设置为false
fileElementId: 'upload_image', //文件上传空间的id属性
dataType: 'json', //返回值类型 一般设置为json
data:{x:global_api.x,y:global_api.y,w:global_api.w,h:global_api.h,pw:boundx,ph:boundy,unid:'test'}, //一同上传的数据 
success: function (data){ //服务器成功响应处理函数
if(data.result){
alert('成功');
}else{
alert('失败');
}
window.location.reload();//刷新当前页面
}
}
);
}
</script>
</html>

后台代码

@ResponseBody
@RequestMapping("uploadphoto")
public Map<String, Object> uploadPhoto(@RequestParam("upimage") MultipartFile imageFile, HttpServletRequest request,
HttpServletResponse response) throws Exception {
Map<String, Object> result = new HashMap<String, Object>();
boolean tag =false;
String unid = request.getParameter("unid");
String x = request.getParameter("x");
String y = request.getParameter("y");
String h = request.getParameter("h");
String w = request.getParameter("w");
// 页面实际图片宽高
String pheight = request.getParameter("ph");
String pweight = request.getParameter("pw");
// 切图参数
int imageX = Integer.parseInt(x);
int imageY = Integer.parseInt(y);
int imageH = Integer.parseInt(h);
int imageW = Integer.parseInt(w);
int srcH = Integer.parseInt(pheight);
int srcW = Integer.parseInt(pweight);
String realPath = request.getSession().getServletContext().getRealPath("/");
String resourcePath = "resources/uploadImages/";
try {
if (imageFile != null) {
if (FileUploadUtil.allowUpload(imageFile.getContentType())) {
// 这里开始截取操作
byte[] b = ImageCut.imgCut(imageFile.getInputStream(), imageX, imageY, imageW, imageH, srcW, srcH);
if (b != null) {
// 存入数据库
User user = userService.selectByPrimaryKey(unid);
user.setPhoto(b);
tag = (userService.updateByPrimaryKeySelective(user)==1)?tag=true:tag;
result.put("result", tag);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
result.put("result", tag);
return result;
}

图像切割工具类

package com.ssm.demo.utils;
import java.awt.Graphics;
import java.awt.Image;
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.ByteArrayOutputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;
public class ImageCut {
/**
* 截取图片
* 
* @param srcImageFile
* 原图片地址
* @param x
* 截取时的x坐标
* @param y
* 截取时的y坐标
* @param desWidth
* 截取的宽度
* @param desHeight
* 截取的高度
* @param srcWidth
* 页面图片的宽度
* @param srcHeight
* 页面图片的高度
* 
*/
public static byte[] imgCut(InputStream input, int x, int y, int desWidth, int desHeight, int srcWidth,
int srcHeight) {
try {
Image img;
ImageFilter cropFilter;
BufferedImage bi = ImageIO.read(input);
if (srcWidth >= desWidth && srcHeight >= desHeight) {
Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);
cropFilter = new CropImageFilter(x, y, desWidth, desHeight);
img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));
BufferedImage tag = new BufferedImage(desWidth, desHeight, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
// 输出文件
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(tag, "JPEG", out);
return out.toByteArray();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

以上所述是小编给大家介绍的JCrop+ajaxUpload 图像切割上传的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Javascript 相关文章推荐
分享别人写的一个小型js框架
Aug 13 Javascript
JavaScript 无符号右移赋值操作
Apr 17 Javascript
jquery实现pager控件示例
Apr 09 Javascript
js操作DOM--添加、删除节点的简单实例
Jul 08 Javascript
阿里云ecs服务器中安装部署node.js的步骤
Oct 08 Javascript
原生js实现轮播图的示例代码
Feb 20 Javascript
jQuery插件FusionCharts实现的2D柱状图效果示例【附demo源码下载】
Mar 06 Javascript
解读vue生成的文件目录结构及说明
Nov 27 Javascript
Vue.directive 自定义指令的问题小结
Mar 04 Javascript
使用webpack搭建react开发环境的方法
May 15 Javascript
layui 富文本图片上传接口与普通按钮 文件上传接口的例子
Sep 23 Javascript
jQuery实现轮播图效果
Nov 26 jQuery
javaScript给元素添加多个class的简单实现
Jul 20 #Javascript
JavaScript中数组的22种方法必学(推荐)
Jul 20 #Javascript
JavaScript DOM 对象深入了解
Jul 20 #Javascript
JavaScript中的splice方法用法详解
Jul 20 #Javascript
Bootstrap被封装的弹层
Jul 20 #Javascript
必备的JS调试技巧汇总
Jul 20 #Javascript
JavaScript的==运算详解
Jul 20 #Javascript
You might like
php定时计划任务的实现方法详解
2013/06/06 PHP
YII Framework框架教程之日志用法详解
2016/03/14 PHP
jQuery性能优化28条建议你值得借鉴
2013/02/16 Javascript
JavaScript Length 属性的总结
2015/11/02 Javascript
基于jquery实现左右按钮点击的图片切换效果
2021/01/27 Javascript
Jquery实现遮罩层的简单实例(就是弹出DIV周围都灰色不能操作)
2016/07/14 Javascript
js轮盘抽奖实例分析
2020/04/17 Javascript
jquery的checkbox,radio,select等方法小结
2016/08/30 Javascript
Javascript 实现放大镜效果实例详解
2016/12/03 Javascript
jQuery实现字体颜色渐变效果的方法
2017/03/29 jQuery
JavaScript数组排序reverse()和sort()方法详解
2017/12/24 Javascript
解决vue-cli创建项目的loader问题
2018/03/13 Javascript
jQuery对底部导航进行跳转并高亮显示的实例代码
2019/04/23 jQuery
Vue 递归多级菜单的实例代码
2019/05/05 Javascript
Vue3 源码导读(推荐)
2019/10/14 Javascript
JS桶排序的简单理解与实现方法示例
2019/11/25 Javascript
ES6 class类链式继承,实例化及react super(props)原理详解
2020/02/15 Javascript
ElementUI Tree 树形控件的使用并给节点添加图标
2020/02/27 Javascript
JavaScript 面向对象程序设计详解【类的创建、实例对象、构造函数、原型等】
2020/05/12 Javascript
[48:26]VGJ.S vs infamous Supermajor 败者组 BO3 第二场 6.4
2018/06/05 DOTA
[46:38]完美世界DOTA2联赛PWL S2 Magma vs PXG 第三场 11.28
2020/12/02 DOTA
详解python中requirements.txt的一切
2017/03/03 Python
不可错过的十本Python好书
2017/07/06 Python
python执行CMD指令,并获取返回的方法
2018/12/19 Python
python基础 range的用法解析
2019/08/23 Python
django 多数据库及分库实现方式
2020/04/01 Python
python自定义函数def的应用详解
2020/06/03 Python
俄罗斯的精英皮具:Wittchen
2018/01/29 全球购物
标签和贴纸印刷:Lightning Labels
2018/03/22 全球购物
英国在线潜水商店:Simply Scuba
2019/03/25 全球购物
学校爱心捐款倡议书
2014/05/13 职场文书
做一个有道德的人演讲稿
2014/05/14 职场文书
2015年公路路政个人工作总结
2015/07/24 职场文书
Python控制台输出俄罗斯方块移动和旋转功能
2021/04/18 Python
用Python实现一个打字速度测试工具来测试你的手速
2021/05/28 Python
Nginx stream 配置代理(Nginx TCP/UDP 负载均衡)
2021/11/17 Servers