简单图片裁剪上传,jsp+servlet+jQuery+Image Cropper(测试)

服务器

 

package test;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.misc.BASE64Decoder;
public class uploadFile extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		String path=getServletContext().getRealPath("/");
		String filePath="upload/";
		
		String msg="default";
		
		/**       base64 图片         **/
		String base64Img=request.getParameter("image");
		BASE64Decoder  decoder=new BASE64Decoder();
		if(base64Img!=null&&!"".equals(base64Img)){
			try {
				byte[] b=decoder.decodeBuffer(base64Img);
				String name=System.currentTimeMillis()+".jpg";
				filePath+=name;
				File file=new File(path+filePath);
				ByteArrayInputStream is=new ByteArrayInputStream(b);
				BufferedImage bi=ImageIO.read(is);
				ImageIO.write(bi, "jpg", file);
				is.close();
				msg="上传成功";
				System.out.println("上传成功!");
			} catch (Exception e) {
				e.printStackTrace();
				msg="上传失败";
				System.err.print("上传失败");
			}
		}else{
			msg="上传失败";
			System.err.print("上传失败");
		}
		response.getWriter().println("{\"msg\":\""+msg+"\",\"imagePath\":\""+filePath+"\"}");
	}
}


jsp

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Cropper</title>
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0" />
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/cropper.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/cropper.css">
<style type="text/css">
body,div,input,ul,li,table,tr,td,textarea,a{margin:0;padding:0;}
input,a{
  box-shadow:0px 0px 10px #000;
  margin:0 auto;
  border-radius:10px;
  color:#fff;
  padding:5px;
  -webkit-appearance:none;
}
</style>

<script type="text/javascript">
	$(function() {
		  var $image = $('#image');
	      var cropBoxData;
	      var canvasData;

	      $('#modal').on('shown.bs.modal', function () {
	        $image.cropper({
	        viewMode : 1,
			dragMode : 'move',
			autoCropArea : 1,
			aspectRatio:1,
			restore : false,
			guides : true,
			highlight : false,
			cropBoxMovable : false,
			cropBoxResizable : false,
	          built: function () {
	            $image.cropper('setCanvasData', canvasData);
	            $image.cropper('setCropBoxData', cropBoxData);
	          }
	        });
	      }).on('hidden.bs.modal', function () {
	        cropBoxData = $image.cropper('getCropBoxData');
	        canvasData = $image.cropper('getCanvasData');
	       // $image.cropper('destroy');
	      });
		
		$("#upload").click(function(){
           var canvas= $("#image").cropper("getCroppedCanvas");
		   var base64=canvas.toDataURL("image/jpeg",0.5);
            $.ajax({
                   url:"uploadFile",
                   type:"post",
                   data:{image:base64.substr(23)},
                   dataType:"json",
                   success:function(data){
                                  alert(data.msg);
                                  $("#showImage").prop("src",data.imagePath);
                           },
                   error:function(){alert("ajax error");}
                });
		});

		$("#selImg").change(function(){
           var file=this.files[0];
           var reader = new FileReader();
   		   reader.onload = function(e) {
   			                       var dataURL = e.target.result; 
   			                       $("#image").cropper('replace', dataURL);
   	                       };
   		   reader.readAsDataURL(file);
		});
	});
</script>
</head>
<body>

    <div class="container">

    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary btn-lg" data-target="#modal" style="margin-top:50px;" data-toggle="modal">裁剪图片</button>

    <!-- show Image -->
    <h3>上传的图片</h3>
    <img src="" id="showImage"  alt="showImage" />
      
    <!-- Modal -->
    <div class="modal fade" id="modal" aria-labelledby="modalLabel" role="dialog" tabindex="-1">
      <div class="modal-dialog" role="document">
        <div class="modal-content" >
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
            <h4 class="modal-title" id="modalLabel">裁剪图片</h4>
          </div>
          <div class="modal-body" style="height:350px;">
            <div style="width:230px;margin:0px auto;">
             <a class="btn btn-primary" href="javascript:void(0)" style="position: relative;height:35px;width:100px;display: block;margin-bottom:10px;float:left;">选择图片
               <input type="file" name="selImg" id="selImg" style="opacity:0;position: absolute;top:0px;left:0px;width:100px;"/>
             </a>
             <input type="button" value="上传图片" id="upload" style="float:left;margin-left:20px;height: 35px;width:100px;" class="btn btn-primary"/>
             <div style="clear:both;"></div>
            </div>
              <img id="image" src="images/dc_bg.jpg" alt="Picture" style="border:1px solid red;">
          </div>
          <div class="modal-footer" style="margin-top:30px">
            <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
          </div>
        </div>
      </div>
    </div>
  </div>

</body>
</html>


web.xml

 

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<servlet>
		<servlet-name>uploadFile</servlet-name>
		<servlet-class>test.uploadFile</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>uploadFile</servlet-name>
		<url-pattern>/uploadFile</url-pattern>
	</servlet-mapping>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

 

 

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

简单就好-怒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值