分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > IT知识

图片裁剪上传Jcrop

发布时间:2023-09-06 02:16责任编辑:苏小强关键词:暂无标签

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

<script src="../js/jquery.Jcrop.js"></script>

先是两个必不可少的东西

<style type="text/css">/* Apply these styles only when #preview-pane has ??been placed within the Jcrop widget */.jcrop-holder #preview-pane { ?display: block; ?position: absolute; ?z-index: 2000; ?top: 10px; ?right: -280px; ?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 crop ??area based on the size of the thumbnail preview, ??specified here */#preview-pane .preview-container { ?width: 250px; ?height: 170px; ?overflow: hidden;}</style>

这是官方的demo中的CSS,预览框所用到的东西,删除之后预览框没有了,一张图在跟着所选区域移动着,因为我用的图片都比较大,所以看着就是一大坨,暂时不知道怎么替换,先放着。

<div style="width:600px; height:400px;" align="center"> ???????????????????????????<img src="../css/657000141504778134.jpg" id="target" alt="[Jcrop Example]" style="max-height: 400px;max-width: 600px;"/> ???????????????????????</div> ???????????????????????<div id="preview-pane"> ???????????????????????????<div class="preview-container" style="width: 180px;height: 180px;background-color:WindowFrame;"> ???????????????????????????????<img src="../css/657000141504778134.jpg" class="jcrop-preview" alt="Preview" /> ???????????????????????????</div> ???????????????????????</div> ???????????????????????<form class="form-horizontal"> ???????????????????????????<div style="margin-top: 10px;"> ???????????????????????????????<button class="btn btn-info">选择图片</button> ???????????????????????????????<div style="margin-top: -40px;" style="cursor: pointer;"> ???????????????????????????????????<input type="file" id="images" name="file" accept="image/gif,image/jpeg,image/x-png" style="opacity: 0;position: relative;height: 40px;" onchange="iferc()"/> ???????????????????????????????</div> ???????????????????????????</div> ???????????????????????</form> ???????????????????????<button class="btn btn-info right" onclick="userImgmit()" style="margin-top: 10px;">保存</button> ???????????????????????<div id="imgx" style="display: none;"></div><!-- 裁剪的X坐标(起点) --> ???????????????????????<div id="imgy" style="display: none;"></div><!-- 裁剪的Y坐标(起点) --> ???????????????????????<div id="imgw" style="display: none;"></div><!-- 裁剪的宽度 --> ???????????????????????<div id="imgh" style="display: none;"></div><!-- 裁剪的高度 --> ???????????????????????<div id="imgurl" style="display: none;"></div><!-- 预览图片的链接 --> ???????????????????????<div id="imgsw" style="display: none;"></div><!-- 预览图片的宽度 -->
<script type="text/javascript">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();$(function(){ ???console.log(‘init‘,[xsize,ysize]); ???$(‘#target‘).Jcrop({ ???????aspectRatio: xsize / ysize ???},function(){ ???????var bounds = this.getBounds(); ???????boundx = bounds[0]; ???????boundy = bounds[1]; ???????jcrop_api = this; ???????$preview.appendTo(jcrop_api.ui.holder); ???});});function updatePreview(c){ ???if (parseInt(c.w) > 0){ ???????var rx = xsize / c.w; ???????var ry = ysize / c.h; ???????$("#imgx").val(c.x); ???????$("#imgy").val(c.y); ???????$("#imgw").val(c.w); ???????$("#imgh").val(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 iferc(){ ???$.ajaxFileUpload({ ???????url:"/Face001/multipleSave", ????????????//需要链接到服务器地址 ???????secureuri:false, ???????type:"post", ???????fileElementId:‘images‘, ????????????????????????//文件选择框的id属性 ???????dataType: ‘text‘, ???????success: function (data, status){ ???????????var start=data.indexOf("{"); ???????????var end=data.indexOf("}"); ???????????var str=data.substring(start,end+1); ???????????var result=JSON.parse(str); ???????????var url = localhostPaht+"/front/"+result.data[0].substring(result.data[0].indexOf("tupian")); ???????????if(jcrop_api != undefined){ ???????????????jcrop_api.destroy(); ???????????} ???????????$("#target").removeAttr(‘src‘); ???????????$("#target").removeAttr(‘style‘); ???????????$("#target").attr(‘style‘,‘max-height: 400px;max-width: 600px;‘); ???????????$("#target").attr(‘src‘,url); ???????????$pimg.removeAttr(‘src‘); ???????????$pimg.attr(‘src‘,url); ???????????$("#imgurl").val(result.data[0].substring(result.data[0].indexOf("tupian"))); ???????????$(‘#target‘).Jcrop({ ???????????????onChange: updatePreview,//截取框改变时调用的方法 ???????????????onSelect: updatePreview,//截取框改变完成时调用的方法 ???????????????aspectRatio: 1 / 1,//截取框的长宽比值,当值为1时截取框大小形状可以随意拖动,因为我截取的是正方形所以是1比1 ???????????????minSize: [50, 50],//截取框最小时的长宽 ???????????????setSelect: [0, 0, 50, 50]//截取框最初的位置和大小,前两个值是截取框的开始位置的X值与Y值,后面两个是截取框的宽度和高度 ???????????},function(){ ???????????????var bounds = this.getBounds(); ???????????????boundx = bounds[0]; ???????????????boundy = bounds[1]; ???????????????jcrop_api = this; ???????????????$preview.appendTo(jcrop_api.ui.holder); ???????????????$("#imgsw").val($(".jcrop-holder img").width()); ???????????}); ???????} ???});}function userImgmit(){ ???if(isDataNullOrEmpty($("#imgurl").val())){ ???????$("#images").tips({ ???????????side : 1, ???????????msg : "请选择图片再进行裁剪上传", ???????????bg : ‘#AE81FF‘, ???????????time : 2 ???????}); ???????return; ???} ???var requestParam = { ???????????imgurl : $("#imgurl").val(), ???????????imgx : $("#imgx").val(), ???????????imgy : $("#imgy").val(), ???????????imgw : $("#imgw").val(), ???????????imgh : $("#imgh").val(), ???????????imgsw : $("#imgsw").val(), ???????????uid : $("#uid").val() ???}; ???sendServerRequest(localhostPaht+"/sys004/userImgMit", requestParam, ???function(returnData){ ???????alert(returnData.message); ???},function(ex){ ???????alert(ex); ???});}</script>

updatePreview 方法就是官方原版的方法,只是在其中将截取的相对位置的几个值赋给了相应的DIV

iferc 方法是图片上传的方法,

$("#target").removeAttr(‘src‘);
$("#target").removeAttr(‘style‘);
$("#target").attr(‘style‘,‘max-height: 400px;max-width: 600px;‘);
$("#target").attr(‘src‘,url);
$pimg.removeAttr(‘src‘);
$pimg.attr(‘src‘,url);

这几行很关键,将预览图片替换掉就是靠这几行完成的

ajaxFileUpload,sendServerRequest,localhostPaht这些都是公司上传提交的方法属性,请根据自身框架更改。

下面是后台代码

/** ????* 保存图片 ????*/ ???public List<String> multipleSave(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception{ ???????if (!file.isEmpty()) { ???????????// 遍历循环 ???????????for (int i = 0; i < file.getSize(); i++) { ???????????????// 获取文件名 ???????????????String fileName = file.getOriginalFilename(); ???????????????// 获取文件的后缀名 ???????????????String suffixName = fileName.substring(fileName.lastIndexOf(".")); ???????????????File path1 = new File(""); ???????????????// 重新定义图片名称 ???????????????fileName = UUID.randomUUID() + suffixName; ???????????????// 获取文件路径 ???????????????File dest = new File(path1.getAbsolutePath() + "/static/front/tupian/" + fileName); ???????????????// 得到文件相对路径准备写入准备好的文件路径中 ???????????????String jue = "../tupian/" + fileName; ???????????????List<String> l = new ArrayList<String>(); ???????????????// 检测是否存在目录 ???????????????if (!dest.getParentFile().exists()) { ???????????????????System.out.println("shifo"); ???????????????????dest.getParentFile().mkdirs(); ???????????????} ???????????????try { ???????????????????file.transferTo(dest); ???????????????} catch (IllegalStateException e) { ???????????????????e.printStackTrace(); ???????????????????jue = "文件不存在"; ???????????????} catch (IOException e) { ???????????????????e.printStackTrace(); ???????????????????jue = "文件不存在"; ???????????????} ???????????????// 准备数据 ???????????????l.add(jue); ???????????????return l; ???????????} ???????} ???????return null; ???}
/** ????* 图片裁剪 ????* @param imgurl 图片链接 ????* @param imgx 截取开始位置X ????* @param imgy 截取开始位置Y ????* @param imgw 截取宽度 ????* @param imgh 截取高度 ????* @param imgsw 预览图片宽度 ????* @param uid ????* @throws Exception ????*/ ???public void userImgMit(String imgurl, Double imgx, Double imgy, Double imgw, Double imgh, Double imgsw, String uid) throws Exception{ ???????File file = new File(""); ???????File file2 = new File(file.getAbsolutePath() + "/static/front/"+imgurl); ???????BufferedImage image = ImageIO.read(new FileInputStream(file2)); ???????double imagew = image.getWidth();//得到图片原本的宽度 ???????double imageh = image.getHeight();//得到图片原本的高度 ???????double x = imagew/imgsw;//缩放比例 ???????if(imgx == -1) { ???????????imgx = 0.0; ???????} ???????if(imgy == -1) { ???????????imgy = 0.0; ???????}
     //计算图片真实截取位置 ???????imgx = imgx*x; ???????imgy = imgy*x; ???????imgw = imgw*x; ???????imgh = imgh*x; ???????Double endx = imgx+imgw; ???????Double endy = imgy+imgh; ???????if(endx > imagew) {//因为缩放比例为double类型,当截取部分包含图片右下角时所计算得到的endx、endy,截取结束位置可能会超过原图的宽高,所以将期重新赋以原图的宽高 ???????????endx = imagew; ???????} ???????if(endy > imageh) { ???????????endy = imageh; ???????} ???????BufferedImage image2 = new BufferedImage(endx.intValue()-imgx.intValue(), endy.intValue()-imgy.intValue(), BufferedImage.TYPE_USHORT_565_RGB); ???????for (int i = imgx.intValue(); i < endx.intValue(); ++i) { ???????????for (int j = imgy.intValue(); j < endy.intValue(); ++j) { ???????????????int rgb = image.getRGB(i, j); ???????????????image2.setRGB(i - imgx.intValue(), j - imgy.intValue(), rgb); ???????????} ???????} ???????// 获取文件的后缀名 ???????String suffixName = imgurl.substring(imgurl.lastIndexOf(".")); ???????// 重新定义图片名称 ???????String fileName = UUID.randomUUID() + suffixName; ???????boolean flase = ImageIO.write(image2, suffixName.substring(1), new File(file.getAbsolutePath() + "/static/front/tupian/" +fileName)); ???????if(!flase) { ???????????throw new MessageException("上传失败"); ???????} ???????mapper2.updateUserImg("../tupian/" + fileName, uid);//这里是我将图片链接存入数据库,不用理会 ???????throw new MessageException("上传成功"); ???}

关于BufferedImage构造方法最后一个参数请参考类BufferedImage,前两个参数为图片真实宽度与高度

最后来张截图

本文参考了多人代码,具体参考了哪几人的我也忘了,本文仅是个人踩坑记录,如有雷同,敬请谅解

图片裁剪上传Jcrop

原文地址:https://www.cnblogs.com/cxcl9225/p/9732592.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved