图片上传,图片剪切jquery.imgareaselect
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了图片上传,图片剪切jquery.imgareaselect相关的知识,希望对你有一定的参考价值。
---恢复内容开始---
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="utf-8" />
<title>广告设置</title>
<%@include file="/common/common.jsp" %>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/jquery.imgareaselect-0.9.10/css/imgareaselect-default.css" />
<script type="text/javascript" src="${pageContext.request.contextPath}/static/jquery.imgareaselect-0.9.10/scripts/jquery.imgareaselect.pack.js"></script>
</head>
<body>
<div class="wrapper details" id="js_layout">
<div class="pad10" id="details_edit" data-options="region:‘center‘">
<table class="forms">
<tbody>
<tr>
<td class="right"><i class="require">*</i>广告图设置方式:</td>
<td><input type="radio" value="1" name="pic" checked="checked" onclick="$(‘.tr1‘).show();$(‘#tr2‘).hide()"/>上传图片
<input type="radio" value="0" name="pic" onclick="$(‘.tr1‘).hide();$(‘#tr2‘).show()"/>设置图片超链接
</td>
</tr>
<tr class="tr1">
<td class="right"><i class="require">*</i>上传图片:</td>
<td>
<form id="form2" method="post" enctype="multipart/form-data">
<input type="file" style="height:22px;" name="advimage" id="advimage" onchange="validateImage();"/>
</form>
</td>
</tr>
<tr class="tr1">
<td class="right"><i class="require">*</i>图片剪切:</td>
<td>
<form id="form1" method="post" enctype="multipart/form-data" >
<img src="" id="left" onclick="imgAreaSelect();">
<input type="hidden" id="x1" value=""/>
<input type="hidden" id="x2" value=""/>
<input type="hidden" id="y1" value=""/>
<input type="hidden" id="y2" value=""/>
<input type="hidden" id="w" value=""/>
<input type="hidden" id="h" value=""/>
<input type="button" value="剪切" onclick="cutImage()"/>
</form>
</td>
</tr>
<tr class="tr1">
<td class="right"><i class="require">*</i>图片预览</td>
<td>
<form id="form3" method="post" enctype="multipart/form-data" >
<img src="" id="leftcut">
<input type="hidden" id="currentPath" value="" name="currentPath">
</form>
</td>
</tr>
<tr id="tr2" style="display: none;">
<td class="right"><i class="require">*</i>公告图超链接:</td>
<td><input type="text" name="picurl" id="picUrl" value="http://js.86269191.com/hgzr/img/22.gif" class="txt easyui-validatebox" data-options="required:true,validType:[‘titleInput‘,‘titlelength[200]‘]"/>
</td>
</tr>
<tr>
<td class="right"><i class="require">*</i>超链接:</td>
<td><input type="text" name="url" id="url" value="http://www.90tuku.com/" class="txt easyui-validatebox" data-options="required:true,validType:[‘titleInput‘,‘titlelength[200]‘]"/>
</td>
</tr>
<tr>
<td class="right"><i class="require">*</i>广告存放位置:</td>
<td><input type="radio" value="left" name="position" checked="checked" />左侧广告
<input type="radio" value="right" name="position"/>右侧广告
</td>
</tr>
</tbody>
</table>
</div>
<!-- <div id="cutImageDiv"> -->
<!-- <div id="cutImageClose">关闭</div> -->
<!-- <div style="margin:0;auto"> -->
<!-- <img src="" id="right" onclick="imgAreaSelect();"> -->
<!-- </div> -->
<!-- </div> -->
<div data-options="region:‘south‘,collapsible:false,height:50" class="noborder hidden">
<div class="ftbutton border-n">
<ul class="lists rf">
<li><button id="_submit" class="button" type="button">上传广告</button></li>
</ul>
</div>
</div>
</div>
<script type="text/javascript" charset="utf-8">
function cutImage(){
var currentPath = $("#currentPath").val();
$.ajax({
type: "POST",
url: "${contextPath}/baAdmin/cutImage.htmls",
data: "x1=" + $("#x1").val()+"&x2="+$("#x2").val()+"&y1="+$("#y1").val()+"&y2="+$("#y2").val()+"&w="+$("#w").val()+"&h="+$("#h").val()+"¤tPath="+currentPath,
success: function(msg){
var json = $.parseJSON(msg);
if(json.success==‘success‘){
$("#currentPath").val(json.currentPath);
$(‘#leftcut‘).attr("src",json.currentPath);
}
}
});
// 这里是利用的dwr框架直接调用后台方法,以及使用后台传回的值
// 这个方法就是利用坐标宽高进行切图,事实上这时候的原图已经在服务器了,所以我们只需要知道他的相对路径,即currentPath
// ReleaseService.cutImage(list, currentPath, function(value){
// document.getElementById("currentPath").value = value;
// }
// );
// var bgObj=document.getElementById("bgDiv");
// var msgObj=document.getElementById("cutImageDiv");
// bgObj.style.display = msgObj.style.display = "none";
// piso.cancelSelection();
// haveImage = 1;
// $(‘#msHaveImage‘).show();
//$(".imgareaselect-outer").hide();
//$(".imgareaselect-selection").parent().hide();
}
function validateImage(){
var imageVal = $(‘#advimage‘).val();
var imageType = imageVal.substr(imageVal.indexOf(‘.‘),imageVal.length);
if(!/.(gif|jp|jpeg|JPG|PNG|png|jpg)$/.test(imageType)){
$.messager.alert(‘警告‘,‘图片类型必须是.jpeg,png,jpg中的一种!‘,‘info‘);
return false;
}
//提交表单
$("#form2").form(‘submit‘,
{
url:"${contextPath}/baAdmin/uploadImageDemo.htmls",
onSubmit:function(){return $(this).form(‘validate‘); },
success : function(d) {
var json = $.parseJSON(d);
if (json.success==‘success‘) {
$(‘#left‘).imgAreaSelect({
x1:0,y1:0,x2:50,y2:50,onSelectEnd:preview,
resizable:false,
instance:true,
persistent:true
});
$(‘#left‘).attr(‘src‘,json.tempPath);
$(‘#currentPath‘).val(json.tempPath);
// ajaxLoadEnd();
// $.messager.alert(‘警告‘,‘备份成功!‘,‘info‘);
}else{
// $.messager.alert(‘警告‘,‘执行失败!‘,‘error‘);
}
}
});
}
// function uploadImage(){
// var imageVal = $(‘#advimage‘).val();
// var imageType = imageVal.substr(imageVal.indexOf(‘.‘),imageVal.length);
// if(!/.(gif|jp|jpeg|JPG|PNG|png)$/.test(imageType)){
// $.messager.alert(‘警告‘,‘图片类型必须是.jpeg,png,jpg中的一种!‘,‘info‘);
// return false;
// }
// $.ajaxFileUpload({
// url:‘${pageContext.request.contextPath}/baAdmin/uploadImage‘,//处理图片脚本
// secureuri :false,
// fileElementId :‘advimage‘,//file控件id
// dataType : ‘json‘,
// success : function (data, status){
// $(‘#photo‘).imgAreaSelect({
// x1:0,y1:0,x2:480,y2:520,onSelectEnd:preview,
// resizable:false,
// instance:true,
// persistent:true
// });
// $(‘#photo‘).attr(‘src‘,data.tempPath);
// },
// error: function(data, status, e){
// alert(e);
// }
// });
// }
function preview(img,selection){
$(‘#x1‘).val(selection.x1);
$(‘#x2‘).val(selection.x2);
$(‘#y1‘).val(selection.y1);
$(‘#y2‘).val(selection.y2);
$(‘#w‘).val(selection.width);
$(‘#h‘).val(selection.height);
}
// function ajaxLoading(){
// $("<div class=\"datagrid-mask\"></div>").css({display:"block",width:"100%",height:$(window).height()}).appendTo("body");
// $("<div class=\"datagrid-mask-msg\"></div>").html("正在处理,请稍候。。。").appendTo("body").css({display:"block",left:($(document.body).outerWidth(true) - 190) / 2,top:($(window).height() - 45) / 2});
// }
// function ajaxLoadEnd(){
// $(".datagrid-mask").remove();
// $(".datagrid-mask-msg").remove();
// }
jQuery(function($){
$("#js_layout").layout({fit:true});
$("#_submit").click( function () {
var pic = $(‘input:radio[name="pic"]:checked‘).val();
var position = $(‘input:radio[name="position"]:checked‘).val();
var url = $(‘#url‘).val();
var picUrl = $(‘#picUrl‘).val();
var file = $(‘#advimage‘).val();
if(pic==‘1‘){
if(file==""){
$.messager.alert(‘提示‘,‘为选择上传图片!!!‘,‘info‘);
return ;
}
}
//提交表单
$("#form3").form(‘submit‘,
{
url:"${contextPath}/baAdmin/imageUploadFinlly.htmls?position="+position+"&pic="+pic+"&url="+url+"&picurl="+picUrl,
onSubmit:function(){return $(this).form(‘validate‘); },
success : function(d) {
var json = $.parseJSON(d);
if (json.success==‘success‘) {
$.messager.alert(‘提示‘,‘左侧广告设置成功!‘,‘info‘);
}
}
});
});
});
</script>
</body>
</html>
---恢复内容结束---
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="utf-8" />
<title>广告设置</title>
<%@include file="/common/common.jsp" %>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/jquery.imgareaselect-0.9.10/css/imgareaselect-default.css" />
<script type="text/javascript" src="${pageContext.request.contextPath}/static/jquery.imgareaselect-0.9.10/scripts/jquery.imgareaselect.pack.js"></script>
</head>
<body>
<div class="wrapper details" id="js_layout">
<div class="pad10" id="details_edit" data-options="region:‘center‘">
<table class="forms">
<tbody>
<tr>
<td class="right"><i class="require">*</i>广告图设置方式:</td>
<td><input type="radio" value="1" name="pic" checked="checked" onclick="$(‘.tr1‘).show();$(‘#tr2‘).hide()"/>上传图片
<input type="radio" value="0" name="pic" onclick="$(‘.tr1‘).hide();$(‘#tr2‘).show()"/>设置图片超链接
</td>
</tr>
<tr class="tr1">
<td class="right"><i class="require">*</i>上传图片:</td>
<td>
<form id="form2" method="post" enctype="multipart/form-data">
<input type="file" style="height:22px;" name="advimage" id="advimage" onchange="validateImage();"/>
</form>
</td>
</tr>
<tr class="tr1">
<td class="right"><i class="require">*</i>图片剪切:</td>
<td>
<form id="form1" method="post" enctype="multipart/form-data" >
<img src="" id="left" onclick="imgAreaSelect();">
<input type="hidden" id="x1" value=""/>
<input type="hidden" id="x2" value=""/>
<input type="hidden" id="y1" value=""/>
<input type="hidden" id="y2" value=""/>
<input type="hidden" id="w" value=""/>
<input type="hidden" id="h" value=""/>
<input type="button" value="剪切" onclick="cutImage()"/>
</form>
</td>
</tr>
<tr class="tr1">
<td class="right"><i class="require">*</i>图片预览</td>
<td>
<form id="form3" method="post" enctype="multipart/form-data" >
<img src="" id="leftcut">
<input type="hidden" id="currentPath" value="" name="currentPath">
</form>
</td>
</tr>
<tr id="tr2" style="display: none;">
<td class="right"><i class="require">*</i>公告图超链接:</td>
<td><input type="text" name="picurl" id="picUrl" value="http://js.86269191.com/hgzr/img/22.gif" class="txt easyui-validatebox" data-options="required:true,validType:[‘titleInput‘,‘titlelength[200]‘]"/>
</td>
</tr>
<tr>
<td class="right"><i class="require">*</i>超链接:</td>
<td><input type="text" name="url" id="url" value="http://www.90tuku.com/" class="txt easyui-validatebox" data-options="required:true,validType:[‘titleInput‘,‘titlelength[200]‘]"/>
</td>
</tr>
<tr>
<td class="right"><i class="require">*</i>广告存放位置:</td>
<td><input type="radio" value="left" name="position" checked="checked" />左侧广告
<input type="radio" value="right" name="position"/>右侧广告
</td>
</tr>
</tbody>
</table>
</div>
<!-- <div id="cutImageDiv"> -->
<!-- <div id="cutImageClose">关闭</div> -->
<!-- <div style="margin:0;auto"> -->
<!-- <img src="" id="right" onclick="imgAreaSelect();"> -->
<!-- </div> -->
<!-- </div> -->
<div data-options="region:‘south‘,collapsible:false,height:50" class="noborder hidden">
<div class="ftbutton border-n">
<ul class="lists rf">
<li><button id="_submit" class="button" type="button">上传广告</button></li>
</ul>
</div>
</div>
</div>
<script type="text/javascript" charset="utf-8">
function cutImage(){
var currentPath = $("#currentPath").val();
$.ajax({
type: "POST",
url: "${contextPath}/baAdmin/cutImage.htmls",
data: "x1=" + $("#x1").val()+"&x2="+$("#x2").val()+"&y1="+$("#y1").val()+"&y2="+$("#y2").val()+"&w="+$("#w").val()+"&h="+$("#h").val()+"¤tPath="+currentPath,
success: function(msg){
var json = $.parseJSON(msg);
if(json.success==‘success‘){
$("#currentPath").val(json.currentPath);
$(‘#leftcut‘).attr("src",json.currentPath);
}
}
});
// 这里是利用的dwr框架直接调用后台方法,以及使用后台传回的值
// 这个方法就是利用坐标宽高进行切图,事实上这时候的原图已经在服务器了,所以我们只需要知道他的相对路径,即currentPath
// ReleaseService.cutImage(list, currentPath, function(value){
// document.getElementById("currentPath").value = value;
// }
// );
// var bgObj=document.getElementById("bgDiv");
// var msgObj=document.getElementById("cutImageDiv");
// bgObj.style.display = msgObj.style.display = "none";
// piso.cancelSelection();
// haveImage = 1;
// $(‘#msHaveImage‘).show();
//$(".imgareaselect-outer").hide();
//$(".imgareaselect-selection").parent().hide();
}
function validateImage(){
var imageVal = $(‘#advimage‘).val();
var imageType = imageVal.substr(imageVal.indexOf(‘.‘),imageVal.length);
if(!/.(gif|jp|jpeg|JPG|PNG|png|jpg)$/.test(imageType)){
$.messager.alert(‘警告‘,‘图片类型必须是.jpeg,png,jpg中的一种!‘,‘info‘);
return false;
}
//提交表单
$("#form2").form(‘submit‘,
{
url:"${contextPath}/baAdmin/uploadImageDemo.htmls",
onSubmit:function(){return $(this).form(‘validate‘); },
success : function(d) {
var json = $.parseJSON(d);
if (json.success==‘success‘) {
$(‘#left‘).imgAreaSelect({
x1:0,y1:0,x2:50,y2:50,onSelectEnd:preview,
resizable:false,
instance:true,
persistent:true
});
$(‘#left‘).attr(‘src‘,json.tempPath);
$(‘#currentPath‘).val(json.tempPath);
// ajaxLoadEnd();
// $.messager.alert(‘警告‘,‘备份成功!‘,‘info‘);
}else{
// $.messager.alert(‘警告‘,‘执行失败!‘,‘error‘);
}
}
});
}
// function uploadImage(){
// var imageVal = $(‘#advimage‘).val();
// var imageType = imageVal.substr(imageVal.indexOf(‘.‘),imageVal.length);
// if(!/.(gif|jp|jpeg|JPG|PNG|png)$/.test(imageType)){
// $.messager.alert(‘警告‘,‘图片类型必须是.jpeg,png,jpg中的一种!‘,‘info‘);
// return false;
// }
// $.ajaxFileUpload({
// url:‘${pageContext.request.contextPath}/baAdmin/uploadImage‘,//处理图片脚本
// secureuri :false,
// fileElementId :‘advimage‘,//file控件id
// dataType : ‘json‘,
// success : function (data, status){
// $(‘#photo‘).imgAreaSelect({
// x1:0,y1:0,x2:480,y2:520,onSelectEnd:preview,
// resizable:false,
// instance:true,
// persistent:true
// });
// $(‘#photo‘).attr(‘src‘,data.tempPath);
// },
// error: function(data, status, e){
// alert(e);
// }
// });
// }
function preview(img,selection){
$(‘#x1‘).val(selection.x1);
$(‘#x2‘).val(selection.x2);
$(‘#y1‘).val(selection.y1);
$(‘#y2‘).val(selection.y2);
$(‘#w‘).val(selection.width);
$(‘#h‘).val(selection.height);
}
// function ajaxLoading(){
// $("<div class=\"datagrid-mask\"></div>").css({display:"block",width:"100%",height:$(window).height()}).appendTo("body");
// $("<div class=\"datagrid-mask-msg\"></div>").html("正在处理,请稍候。。。").appendTo("body").css({display:"block",left:($(document.body).outerWidth(true) - 190) / 2,top:($(window).height() - 45) / 2});
// }
// function ajaxLoadEnd(){
// $(".datagrid-mask").remove();
// $(".datagrid-mask-msg").remove();
// }
jQuery(function($){
$("#js_layout").layout({fit:true});
$("#_submit").click( function () {
var pic = $(‘input:radio[name="pic"]:checked‘).val();
var position = $(‘input:radio[name="position"]:checked‘).val();
var url = $(‘#url‘).val();
var picUrl = $(‘#picUrl‘).val();
var file = $(‘#advimage‘).val();
if(pic==‘1‘){
if(file==""){
$.messager.alert(‘提示‘,‘为选择上传图片!!!‘,‘info‘);
return ;
}
}
//提交表单
$("#form3").form(‘submit‘,
{
url:"${contextPath}/baAdmin/imageUploadFinlly.htmls?position="+position+"&pic="+pic+"&url="+url+"&picurl="+picUrl,
onSubmit:function(){return $(this).form(‘validate‘); },
success : function(d) {
var json = $.parseJSON(d);
if (json.success==‘success‘) {
$.messager.alert(‘提示‘,‘左侧广告设置成功!‘,‘info‘);
}
}
});
});
});
</script>
</body>
</html>
/**
* springmvc 上传文件
* @return
*/
@ResponseBody
@RequestMapping("/uploadImageDemo")
public Object uploadImageDemo(@RequestParam(value="advimage",required=false) MultipartFile file, HttpServletRequest request, ModelMap model){
Map<String, Object> resultMap = new HashMap<String, Object>();
System.out.println("开始");
String path = request.getSession().getServletContext().getRealPath("upload");
// String cutpath = request.getSession().getServletContext().getRealPath("cutUpload");
String fileName = file.getOriginalFilename();
System.out.println(path);
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
//保存
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
resultMap.put("tempPath", request.getContextPath()+"/upload/"+fileName);
resultMap.put("success", "success");
return resultMap;
}
@ResponseBody
@RequestMapping("/cutImage")
public Object cutImage(HttpServletRequest request, HttpServletResponse response) {
Map<String, Object> restMap = new HashMap<String, Object>();
String x11 = request.getParameter("x1");
String x22 = request.getParameter("x2");
String y11 = request.getParameter("y1");
String y22 = request.getParameter("y2");
String ww= request.getParameter("w");
String hh = request.getParameter("h");
String path = request.getParameter("currentPath");
int x1 = Integer.parseInt(x11);
int x2 = Integer.parseInt(x22);
int y1 = Integer.parseInt(y11);
int y2 = Integer.parseInt(y22);
int w = Integer.parseInt(ww);
int h = Integer.parseInt(hh);
if(w <= 0)
w = 120;
if(h<=0)
h = 120;
if(x1<0)
x1 = 0;
if(y1<0)
y1 = 0;
//File file = new File(request.getSession().getServletContext().getRealPath(path));
// path = path.substring(2);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String file_ext = path.substring(path.indexOf("."),path.length());
String uploadpath = request.getSession().getServletContext().getRealPath("upload");
File file = new File(request.getSession().getServletContext().getRealPath(uploadpath));
String imageName =df.format(new Date())+UUIDUtils.getUUID32() + file_ext;
String newFile = uploadpath +"/"+imageName;
//切图操作
abscut(request.getSession().getServletContext().getRealPath(path), newFile, x1, y1, w, h);
// File targetFile = new File(path, fileName);
// if(!targetFile.exists()){
// targetFile.mkdirs();
// }
//
// //保存
// try {
// file.transferTo(targetFile);
// } catch (Exception e) {
// e.printStackTrace();
// }
restMap.put("success", "success");
restMap.put("currentPath", request.getContextPath()+"/upload/"+imageName);
return restMap;
// return BusinessConstants.TEMP_RELATIVE_PICTURE_PATH + imageName;
}
public static void abscut(String srcImageFile,String desImageFile, int x, int y,int width, int height) {
try {
Image img;
ImageFilter cropFilter;
File srcFile = new File(srcImageFile);
//String fileName = srcFile.getName();
String ext = getExtension(srcImageFile);
if(ext==null)ext="jpg";
// 读取源图像
BufferedImage bi = ImageIO.read(srcFile);
int srcWidth = bi.getWidth(); // 源图宽度
int srcHeight = bi.getHeight(); // 源图高度
if (srcWidth >= width && srcHeight >= height) {
BufferedImage tag;
Image image = bi.getScaledInstance(srcWidth, srcHeight,Image.SCALE_DEFAULT);
// 四个参数分别为图像起点坐标和宽高
// 即: CropImageFilter(int x,int y,int width,int height)
cropFilter = new CropImageFilter(x, y, width, height);
img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));
int type = BufferedImage.TYPE_INT_RGB;
if("gif".equalsIgnoreCase(ext)||"png".equalsIgnoreCase(ext)){
type = BufferedImage.TYPE_INT_ARGB;
}
tag = new BufferedImage(width, height,type);
Graphics2D g = (Graphics2D)tag.getGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(img, 0, 0, null); // 绘制剪切后的图
g.dispose();
ImageIO.write(tag,ext, new File(desImageFile));
srcFile.delete();//删除原图
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getExtension(String srcImageFile) {
String ext = null;
if(srcImageFile!=null && srcImageFile.lastIndexOf(".")>-1){
ext = srcImageFile.substring(srcImageFile.lastIndexOf(".")+1);
}
return ext;
}
以上是关于图片上传,图片剪切jquery.imgareaselect的主要内容,如果未能解决你的问题,请参考以下文章
uni-app图片剪切上传;uview2用使用uview1中的图片剪切上传组件,把原有代码抽取出来
js无刷新上传图片,服务端有生成缩略图,剪切图片,iphone图片旋转判断功能