Jcrop+ajaxFileUpload 图片裁切上传 oss(java web)

13 篇文章 0 订阅
9 篇文章 0 订阅

代码资源地址:http://download.csdn.net/download/weixin_30512027/10163387

html代码:imageFile用来选择文件 url用来放上传之后的图片地址 x、y、w、h为裁切参数 iframe为图片裁切框每选择一次都要重新加载否则jcrop不会改变

<input id="url" value="${cmsFile.url }" name="url" htmlEscape="false" maxlength="512" class="input-xlarge required" /> 
<input id="imageFile" name="picUrl" type="file" accept="image/*">
<button id="upCrop" type="button">图片上传</button>					
<div class="inline-labels" style="display: none">
    <label>X1 <input type="text" size="4" id="x1" name="x1" /></label>
    <label>Y1 <input type="text" size="4" id="y1" name="y1" /></label>
    <label>X2 <input type="text" size="4" id="x2" name="x2" /></label>
    <label>Y2 <input type="text" size="4" id="y2" name="y2" /></label>
    <label>W <input type="text" size="4" id="w" name="w" /></label>
    <label>H <input type="text" size="4" id="h" name="h" /></label>
</div>
<iframe src="javascript:;" id="iframeC" name="iframeC" frameborder="0" width="100%"
					 style="border:0px; display: none;" border="0" marginwidth="0" marginheight="0" scrolling="auto" allowtransparency="yes"></iframe>js 

js代码:

$('#upCrop').click(function(){
							var x,y,w,h;
							x=$('#x1').val();
							y=$('#y1').val();
							w=$('#w').val();
							h=$('#h').val();
							$.ajaxFileUpload({
								url : ctx + "/cms/cmsFile/fileUpload.do",// 默认为post请求
								secureuri : false, // 是否启用安全提交,默认为false
								fileElementId : 'imageFile', // 文件选择框的id属性
								method : 'POST',
								data : {
									"x":x,
						            "y":y,
						            "w":w,
						            "h":h,
									format : 'json'
								},// 告诉服务器请给我返回json格式的数据,spring mvc内容协商支持本参数
								dataType : 'json',// 本组件按什么格式接收服务器返回的数据,可以是json或xml等,空表示直接返回data
								fileSize : 5242880,// 文件大小限制,可选,0 为无限制(IE浏览器不兼容)
								allowType : 'jpg,jpeg,png,bmp',// 可选,限定上传文件的格式
								success : function(data) {
									$('#url').val(data.imagePath);
								},
								error : function(data) { // 服务器响应失败时的处理函数
									showTip('上传失败,请重试!!','',500,500);
								}
							}); 
						})
						
						var file;
						$('#imageFile')
								.change(
										function() {
											//document.getElementById('iframeC').contentWindow.location.reload(true)
											file = this.files[0];
											document.getElementById('iframeC').src = ctxStatic
													+ '/jcrop/demos/tutorial2.html';
											var file = this.files[0];

											var reader = new FileReader();
											reader.onload = function() {
												// 通过 reader.result 来访问生成的 DataURL
												var url = reader.result;
												setImageURL(url);
											};
											reader.readAsDataURL(file);
										});
						var image = new Image();
						function setImageURL(url) {
							image.src = url;
							//	$('.container').html(image);
							//	image.id = "imgView";
							//var imgV = $('#imgView');
							//$("#iframeC").contents().find("#target").attr('src',url);
									var iframe = document.getElementById("iframeC"); 

							if (iframe.attachEvent){ 
							iframe.attachEvent("onload", function(){ 
								alert("Local iframe is now loaded."); 
							}); 
							} else { 
							iframe.onload = function(){ 
							//alert("Local iframe is now loaded."); 
							$('#upCrop').show();
							$('#iframeC').show();
							setIframeHeight(this)
								$('#target',
										document.getElementById("iframeC").contentWindow.document)
										.attr('src', url);
								$('#target',
										document.getElementById("iframeC").contentWindow.document)
										.click();
							}; 
							} 
							
						}



图片裁切jcrop页面代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Basic Handler | Jcrop Demo</title>
  <meta http-equiv="Content-type" content="text/html;charset=UTF-8" />

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

  jQuery(function($){
	  $('#target').click(
				function() {
					var jcrop_api;

				    $('#target').Jcrop({
				      onChange:   showCoords,
				      onSelect:   showCoords,
				      onRelease:  clearCoords,
				      bgOpacity : 0.5,
					  bgColor : 'white',
					  addClass : 'jcrop-light',
					  baseClass: 'jcrop',
				    },function() {
				    	jcrop_api = this;
				    	jcrop_api.setSelect([ 130, 65, 130 + 380,
								65 + 255 ]);
				    	jcrop_api.setOptions({
							bgFade : true
						});
				    	jcrop_api.ui.selection
								.addClass('jcrop-selection');
					});

				    $('#coords').on('change','input',function(e){
				      var x1 = $('#x1').val(),
				          x2 = $('#x2').val(),
				          y1 = $('#y1').val(),
				          y2 = $('#y2').val();
				      jcrop_api.setSelect([x1,y1,x2,y2]);
				    });
				})
    

  });

  // Simple event handler, called from onChange and onSelect
  // event handlers, as per the Jcrop invocation above
  function showCoords(c)
  {
    $('#x1',parent.document).val(c.x);
    $('#y1',parent.document).val(c.y);
    $('#x2',parent.document).val(c.x2);
    $('#y2',parent.document).val(c.y2);
    $('#w',parent.document).val(c.w);
    $('#h',parent.document).val(c.h);
  };

  function clearCoords()
  {
    $('#coords input').val('');
  };

</script>
<link rel="stylesheet" href="demo_files/main.css" type="text/css" />
<link rel="stylesheet" href="demo_files/demos.css" type="text/css" />
<link rel="stylesheet" href="../css/jquery.Jcrop.css" type="text/css" />

</head>
<body>
<div class="jc-demo-box" style="text-align: center;width:500px;height:500px">
  <img src="" id="target" alt="[Jcrop Example]" width="500px" style="margin: 0 auto;"/>

</div>
</body>
</html>


java后台代码:

@RequestMapping(value = "fileUpload")
	@ResponseBody
	public Map<String, String> fileUpload(@RequestParam(value = "picUrl") MultipartFile picUrl, @RequestParam String x,
			@RequestParam String y, @RequestParam String w, @RequestParam String h) throws IOException {
		String refileName = "";
		if (picUrl != null) {
			String fileName = picUrl.getOriginalFilename();
			byte[] data = null;
			InputStream fis = null;
			ImageInputStream iis = null;
			try {
				if (picUrl.getBytes().length < 5242880 && FileUtils.isImg(fileName)) {
					data = picUrl.getBytes();
					String imageFormat = FileUtils.fileSuff(fileName);
					fis = picUrl.getInputStream();
					Iterator it = ImageIO.getImageReadersByFormatName(imageFormat);
					ImageReader reader = (ImageReader) it.next();
					// 获取图片流
					iis = ImageIO.createImageInputStream(fis);
					reader.setInput(iis, true);
					ImageReadParam param = reader.getDefaultReadParam();
					// 定义一个矩形
					Rectangle rect = new Rectangle(Integer.parseInt(x), Integer.parseInt(y), Integer.parseInt(w),
							Integer.parseInt(h));
					// 提供一个 BufferedImage,将其用作解码像素数据的目标。
					param.setSourceRegion(rect);
					BufferedImage bi = reader.read(0, param);
					// 保存新图片
					File file = multipartToFile(picUrl,imageFormat);
					ImageIO.write(bi, imageFormat, file);
					refileName = OSSUnit.uploadObject2OSS(file);
				} else {
					logger.debug("文件大于5M或者文件类型不正确!");
				}
			} catch (IOException e1) {
				logger.debug("文件上传失败" + e1);
			} finally {
				if (fis != null)
					fis.close();
				if (iis != null)
					iis.close();
			}
		}
		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put("imagePath", refileName);
		return jsonMap;// 返回json串
	}
	



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ASP.NET MVC4中可以使用JCrop插件进行图片裁剪,并通过Ajax上传裁剪后的图片。以下是实现步骤: 1. 引入JCrop插件和jQuery库。 2. 在视图中添加一个图片标签和一个用于显示裁剪后图片的标签。 ```html <div> <img src="原始图片路径" id="crop-img" /> </div> <div> <img src="" id="crop-result" /> </div> ``` 3. 在JavaScript中初始化JCrop插件。 ```javascript $(function() { $('#crop-img').Jcrop({ aspectRatio: 1, // 宽高比 onSelect: updateCoords // 选择区域后的回调函数 }); }); ``` 4. 编写回调函数updateCoords,获取裁剪后的坐标值。 ```javascript function updateCoords(c) { $('#x').val(c.x); $('#y').val(c.y); $('#w').val(c.w); $('#h').val(c.h); } ``` 5. 添加表单,包含用于保存坐标值的隐藏输入框和一个上传按钮。 ```html <form id="crop-form" method="post" enctype="multipart/form-data"> <input type="hidden" id="x" name="x" /> <input type="hidden" id="y" name="y" /> <input type="hidden" id="w" name="w" /> <input type="hidden" id="h" name="h" /> <input type="file" id="file" name="file" /> <button type="submit" id="submit">上传</button> </form> ``` 6. 绑定上传按钮点击事件,在点击上传按钮时使用Ajax上传裁剪后的图片。 ```javascript $('#submit').click(function() { var formData = new FormData($('#crop-form')[0]); $.ajax({ type: 'post', url: '上传图片的URL', data: formData, processData: false, contentType: false, success: function(data) { $('#crop-result').attr('src', '上传后的图片路径'); }, error: function() { alert('上传失败'); } }); return false; }); ``` 以上就是使用JCrop插件进行图片裁剪并上传的步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值