springMVC+jcrop实现头像上传截图功能
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Jsp开发头像裁剪</title>
<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
<script type="text/javascript" src="/js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="/js/jquery-ui.min.js"></script>
<script type="text/javascript" src="js/jquery.Jcrop.min.js"></script>
<script type="text/javascript" src="/js/ajaxfileupload.js"></script>
<style type="text/css">
*{margin: 0;padding: 0;}
.cut{
margin-top: 20px;
}
#preview-pane {
display: block;
position: absolute;
z-index: 2000;
top: 10px;
right: -480px;
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);
}
#preview-pane .preview-container {
width: 250px;
height: 170px;
overflow: hidden;
}
</style>
<script type="text/javascript">
$(function(){
var jcrop_api,
boundx="",
boundy="",
$preview = $('#preview-pane'),
$pcnt = $('#preview-pane .preview-container'),
$pimg = $('#preview-pane .preview-container img'),
xsize = $pcnt.width(),
ysize = $pcnt.height();
$('#cutImage').Jcrop({
onChange:showCoords,//获取选中的值
onSelect:showCoords,//获取拖拽的值
aspectRatio: xsize / ysize
},function(){
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
$('#imgW').val(boundx);
$('#imgH').val(boundy);
jcrop_api = this;
$preview.appendTo(jcrop_api.ui.holder);
});
function showCoords(c){
var x=c.x;
var y=c.y;
var w=c.w;
var h=c.h;
$("#x1").val(parseInt(x));
$("#y1").val(parseInt(y));
$("#w").val(parseInt(w));
$("#h").val(parseInt(h));
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'
});
}
}
});
function uploadImg() {
$.ajaxFileUpload({
url:'/file/uploadImg',
secureuri:false,
fileElementId:'fileId',//file控件的id
dataType: 'json',//返回数据的类型
data:{},//一同上传的数据
success:function(data, status){
if (data.state == 1) {
var path = data.path;
$('#imgPath').val(path);
$("img").attr('src', path);
} else if (data.state == -1) {
alert('图片格式错误');
} else if (data.state == -2) {
alert('上传文件过大');
} else if (data.state == -3) {
alert('图片尺寸不正确');
} else {
alert('上传失败');
}
}
});
}
</script>
</head>
<body>
<h1>头像裁剪系统</h1>
<div class="cut">
<img id="cutImage" alt="" src="/imgs/timg.jpg" width="600">
<input type="file" id="fileId" name="ufile" class="absolute edithead_file" value="" οnchange="uploadImg()"/>
<div id="preview-pane">
<div class="preview-container">
<img src="/imgs/timg.jpg" class="jcrop-preview" alt="Preview" id="imageJcrop" />
</div>
</div>
</div>
<form action="/screenshot" method="post" >
<input type="hidden" name="imgPath" id="imgPath" value="/imgs/timg.jpg">
<input type="hidden" id="imgW" name="imgW" />
<input type="hidden" id="imgH" name="imgH" />
x轴:<input type="text" size="4" id="x1" name="x" />
y轴:<input type="text" size="4" id="y1" name="y"/>
宽度:<input type="text" size="4" id="w" name="w"/>
高度:<input type="text" size="4" id="h" name="h"/>
<input type="submit" value="裁剪"/>
</form>
</body>
</html>
ajax上传图片方法:
//img.path=D:/tomcat/8080/webapps/dspimg
//img.url=http://localhost:8080/dspimg
private static final String INPUT_NAME = "ufile"; //上传控件名
@Value("${img.path}")
private String imgpath; //文件服务器物理路径
@Value("${img.url}")
private String imgurl; //文件服务器访问路径
@Value("${img.ext}")
private String imgext; //可上传图片后缀,格式 *.bmp;*.gif;*.jpg;*.jpeg;*.png;
@Value("${img.maxsize}")
private String imgmaxsize; //图片最大多少k
/**
* 图片上传
* @param request
* @param width 限制宽
* @param height 限制高
* @param maxLength 限制大小,单位kb
* @param exts 可用后缀,格式: jpg,jpeg,png
* @return
*/
@ResponseBody
@RequestMapping("uploadImg")
public String uploadImg(HttpServletRequest request, Integer width, Integer height, Integer maxLength, String exts) {
FileBean fileBean = new FileBean();
/** 文件信息 **/
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile(INPUT_NAME);
String fileName = file.getOriginalFilename(); // 获得文件名
String ext = fileName.substring(fileName.lastIndexOf(".") + 1); // 后缀
//文件格式是否正确
if (!StringUtil.isBlank(exts)) {
if (exts.toLowerCase().indexOf(ext.toLowerCase()) == -1) {
log.error("图片格式错误");
fileBean.setState(-1);
return JsonUtil.json2Str(fileBean);
}
} else if (!validateImg(ext)) {
log.error("图片格式错误");
fileBean.setState(-1);
return JsonUtil.json2Str(fileBean);
}
Long fileSize = file.getSize();
//文件大小是否超标
if (maxLength != null && maxLength > 0) {
Long maxSize = (long) (maxLength * 1024.0);
if (fileSize > maxSize) {
log.error("文件大小超标");
fileBean.setState(-2);
return JsonUtil.json2Str(fileBean);
}
}
//获取图片属性
BufferedImage img = null;
try {
img = ImageIO.read(file.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
int w = img.getWidth();
int h = img.getHeight();
//判断图片尺寸是否符合要求
if (width != null && height != null) {
if (w != width || h != height) {
log.error("图片尺寸不正确");
fileBean.setState(-3);
return JsonUtil.json2Str(fileBean);
}
}
/** 上传文件 **/
String newFileName = GlobalUtil.createFileName(ext); //新文件名
String newFilePath = imgpath + "/temp/" + newFileName; //新文件全路径
//创建目录
File pathDir = new File(imgpath + "/temp/");
if (!pathDir.exists()) {
pathDir.mkdirs();
}
//上传
File uploadFile = new File(newFilePath);
try {
FileCopyUtils.copy(file.getBytes(), uploadFile);
} catch (IOException e) {
e.printStackTrace();
}
/** 组装FileBean list **/
String newFileUrl = imgurl + "/temp/" + newFileName; //访问路径
fileBean.setPath(newFileUrl);
fileBean.setName(fileName);
fileBean.setNewName(newFileName);
fileBean.setExt(ext);
fileBean.setSize(fileSize);
fileBean.setSizeStr(CommonUtil.formatDataSize(file.getSize()));
fileBean.setWidth(w);
fileBean.setHeight(h);
//封装json对象
String jsonData = JsonUtil.json2Str(fileBean);
return jsonData;
}
/**
* @return 截图方法
*/
@RequestMapping(value = "screenshot", method = RequestMethod.POST)
public String screenshot(String imgPath,Integer x, Integer y, Integer w, Integer h,Integer imgW,Integer imgH) {
imgPath=imgPath.indexOf(imgurl)!=-1?imgPath:imgurl+imgPath;
ImageCut cut = new ImageCut();
UUser user = updateUfile(getSessionAdver(),imgPath.substring(imgPath.lastIndexOf("/")+1, imgPath.length()));
cut.cutImage(imgpath+user.getImg(),x,y,w,h,imgW,imgH);
put("userImg",imgurl+user.getImg());
return "/common/jcrop/image";
}
/**
* 获取图片新路径
* @param userId
* @param imgUrl
*/
public UUser updateUfile(UUser user, String imgHead) {
if (!StringUtil.isBlank(imgHead)) {
//保存头像
String tempPath = imgpath + "/temp/" + imgHead; //图片临时目录
String newRoot = imgpath + "/user/" + user.getId() + "/";
String newPath = newRoot + imgHead;
String savePath = "/user/" + user.getId() + "/" + imgHead;
File root = new File(newRoot);
try {
FileCopyUtils.copy(new File(tempPath), new File(newPath));
} catch (IOException e) {
e.printStackTrace();
}
user.setImg(savePath);
}
return user;
}
截图类
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.Graphics;
import javax.imageio.ImageIO;
public class ImageCut {
public void cutImage(String imagePath, int x ,int y ,int w,int h,int imgW,int imgH){
try {
Image img;
ImageFilter cropFilter;
// 读取源图像
BufferedImage bi = ImageIO.read(new File(imagePath));
int srcWidth = bi.getWidth(); // 源图宽度
int srcHeight = bi.getHeight(); // 源图高度
//若原图大小大于切片大小,则进行切割
if (srcWidth >= w && srcHeight >= h) {
Image image = bi.getScaledInstance(srcWidth, srcHeight,Image.SCALE_DEFAULT);
int x1 = x*srcWidth/imgW;
int y1 = y*srcHeight/imgH;
int w1 = w*srcWidth/imgW;
int h1 = h*srcHeight/imgH;
cropFilter = new CropImageFilter(x1, y1, w1, h1);
img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));
BufferedImage tag = new BufferedImage(w1, h1,BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(img, 0, 0, null); // 绘制缩小后的图
g.dispose();
// 输出为文件
ImageIO.write(tag, "JPEG", new File(imagePath));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
springMVC+jcrop实现头像上传截图功能相关推荐
- 小程序图片裁剪插件image-cropper实现个人头像上传裁剪功能
小程序图片裁剪插件image-cropper实现个人头像上传裁剪功能 参考文档:小程序图片裁剪插件 image-cropper 整体效果流程图 一.第一步引入image-cropper,放在dist文 ...
- php jcrop教程,PHP+Jcrop+artDialog头像上传
上节课我们讲解了artDialog强大的弹出层插件,本文以实例讲解个人中心常用的头像裁剪. 下载资源 下载积分: 120 积分 HTML PHP+Jcrop+artDialog头像上传 引入jQuer ...
- Android实现注册登录头像上传等功能常规开发(Android端,服务器端开发实例)
Android实现注册登录头像上传等功能常规开发(Android端,服务器端开发实例) 标签: 注册登录Android开发servlet 2017-04-18 20:34 454人阅读 评论(1) ...
- SpringMVC Web实现文件上传下载功能实例解析
需求: 项目要支持大文件上传功能,经过讨论,初步将文件上传大小控制在20G内,因此自己需要在项目中进行文件上传部分的调整和配置,自己将大小都以20G来进行限制. PC端全平台支持,要求支持Window ...
- web实现QQ头像上传截取功能
由于最近一段时间比较忙,发现好久没写博客了,给大家分享下最近搞的logo上传截取功能.在实现这个功能之前找了一些jq的插件,最后选定了cropper在github中可以找到. 具体的思路是1:选择上传 ...
- vue 头像上传裁剪功能
1,第一步安装vue-cropper cnpm install vue-cropper 2,在main.js引用 import VueCropper from 'vue-cropper'; Vue.u ...
- Android--利用Bmob实现头像上传下载功能
声明: 本文使用Bmob作为云后台,实现一个简简单单的头像的选取.截取.上传.下载功能的实现. 编码环境:Android Studio2.1.1 运行环境:Miui8.6.8.18(安卓版本号6.0. ...
- 调用android的拍照或本地相册选取再实现相片上传服务器,Android调用系统相机、本地相册上传图片(头像上传(裁剪)、多张图片上传)...
开发中基本上都会有头像上传的功能,有的app还需要多张图片同时上传,下面简单将头像上传以及多张图片上传功能整理一下.图片选择仿照微信选择图片的界面.[参考] 多图片选择器 !!!推荐一个动态权限请求的 ...
- 【Bootstrap-插件使用】Jcrop+fileinput组合实现头像上传功能
作者:Dreawer 链接:https://zhuanlan.zhihu.com/p/24465742 来源:知乎 著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. 作者:梦游的龙 ...
最新文章
- jQuery对象和DOM对象使用说明
- javascript 仿 C# format
- php加密解密p源码可以吗,论 如何做好PHP的加密解密呐,源码教学
- 《SAP CRM管理与实施指南》一一2.2 SAP CRM基础功能
- centos7.2 安装mysql5.6_Centos7安装mysql5.6
- recorder-list
- 好好说说Java中的常量池之Class常量池 1
- java继承原理内存角度_Java编程的逻辑 (17) - 继承实现的基本原理
- nginx并发性能测试
- Django从入门到放弃
- C++:STL之vector,deque对比
- #地形剖面图_备战中考 地理图表判读——地形剖面图
- Vulnhub-HackInOS
- 记一次mybatis-plus遇到的问题
- Redis 入门指南(五)管理
- 微型计算机系统结构中的总线,微型计算机的总线结构
- 两角和与差的余弦公式的五种推导方法之对比
- 死亡时间推断MATLAB,AGU 本周精选文章:火星陨石坑;气候敏感性;水资源压力;洪水灾害建模...
- OpenCV--011:像素归一化
- java poi 读取 word图片_Java Poi 根据文字内容 插入 word 图片-Go语言中文社区
热门文章
- 《Android Studio应用开发实战详解》版权信息
- 2023年“呕心沥血”之泰迪杯数据挖掘A题新冠疫情比赛经历分享
- 东南亚来信 | 专访Komodo创始人Ben
- 关于PMP认证的那些事儿
- 戴尔服务器型号720xd,Dell PowerEdge R720/R720xd服务器,各有侧重双子星
- NTFS安全权限 3th
- 怎样使一排文字中间有间隔_Word如何调整字间距,行间距
- cubemx万年钟_一知半解学CubeMX——TIM:定时中断实现LED闪烁
- STC15单片机-LED闪烁(面向对象程序结构)
- mysql 设置计算列_mysql – 创建计算列