JQuery 图像裁剪插件Jcrop实现图片上传功能(mysql DB)

需求

最近在做一个企业设置的模块,要求可以上传企业logo到mysql数据库当中,在企业登录首页的时候,就可以显示出来这个logo。我实现这个功能使用了一个JQ的插件,可以裁剪上传的图片,实现logo的简单处理制作。

代码实现

  • 引用Jcrope 的包在jsp中


<script type="text/javascript"
    src="${pageContext.request.contextPath}/common/tapmodo-Jcrop-v0.9.12-0-g1902fbc/tapmodo-Jcrop-1902fbc/js/jquery.min.js">script>
<%@ include file="/common.jsp"%>
<script type="text/javascript"
    src="${pageContext.request.contextPath}/common/tapmodo-Jcrop-v0.9.12-0-g1902fbc/tapmodo-Jcrop-1902fbc/js/jquery.Jcrop.js">script>

<link
    href="${pageContext.request.contextPath}/common/tapmodo-Jcrop-v0.9.12-0-g1902fbc/tapmodo-Jcrop-1902fbc/demos/demo_files/main.css"
    rel="stylesheet" type="text/css" />
<link
    href="${pageContext.request.contextPath}/common/tapmodo-Jcrop-v0.9.12-0-g1902fbc/tapmodo-Jcrop-1902fbc/demos/demo_files/demos.css"
    rel="stylesheet" type="text/css" />
<link
    href="${pageContext.request.contextPath}/common/tapmodo-Jcrop-v0.9.12-0-g1902fbc/tapmodo-Jcrop-1902fbc/css/jquery.Jcrop.css"
    rel="stylesheet" type="text/css" />
  • 视图
<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);
}

#preview-pane .preview-container {
    width: 250px;
    height: 170px;
    overflow: hidden;
}
/*  预览图片的样式 */
/* 企業LOGO和選擇圖片顯示的邊框樣式---開始  */
img.double-border {
    border: 2px solid #ddd;
    padding:2px;
    background: #fff;
}
/* 企業LOGO和選擇圖片顯示的邊框樣式---结束  */

/*改变file的默认样式开始---赋值的没有办法将easyui-linkbutton的样式直接赋给它,只有将原原来的样式赋给控件 */
::-webkit-file-upload-button {
    line-height: 25px;
    color: #444;
    background: #fafafa;
    background-repeat: repeat-x;
    border: 1px solid #bbb;
    background: -webkit-linear-gradient(top, #ffffff 0, #eeeeee 100%);
    background: -moz-linear-gradient(top, #ffffff 0, #eeeeee 100%);
    background: -o-linear-gradient(top, #ffffff 0, #eeeeee 100%);
    background: linear-gradient(to bottom, #ffffff 0, #eeeeee 100%);
    background-repeat: repeat-x;
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffff, endColorstr=#eeeeee, GradientType=0);
    -moz-border-radius: 5px 5px 5px 5px;
    -webkit-border-radius: 5px 5px 5px 5px;
    border-radius: 5px 5px 5px 5px;
    font-size: 12px; /*裡面文字的大小---“选择文件”  */
    font-family:sans-serif; /*文字的类型  */
}
/*改變file的默認樣式結束 */
style>


<script type="text/javascript">
    //定义一个全局api,这样操作起来比较灵活
    var jcrop_api, boundx, boundy;
    function readURL(input) {

        $preview = $('#preview-pane'),
                $pcnt = $('#preview-pane .preview-container'),
                $pimg = $('#preview-pane .preview-container img'),
                xsize = $pcnt.width(), ysize = $pcnt.height();
        console.log('init', [ xsize, ysize ]);

        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.readAsDataURL(input.files[0]);

            reader.onload = function(e) {
                /*  $('#cutimg').removeAttr('src');
                 $('#cutimg').attr('src', e.target.result); */
                //
result.innerHTML = ''" alt="" />'; $('#cutimgPreview').removeAttr('src'); $('#cutimgPreview').attr('src', e.target.result); //alert(e.target.result); $('#result').Jcrop({ onChange : updatePreview, onSelect : updatePreview, /* aspectRatio : xsize / ysize /* 选框宽高比。说明:width/height */ }, function() { // Use the API to get the real image size var bounds = this.getBounds(); boundx = bounds[0]; boundy = bounds[1]; // Store the API in the jcrop_api variable jcrop_api = this; // Move the preview into the jcrop container for css positioning $preview.appendTo(jcrop_api.ui.holder); }); } } function updatePreview(c) { $("#x").val(c.x); $("#y").val(c.y); $("#w").val(c.w); $("#h").val(c.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' }); } } } //修改logo后返回企业设置 function fanhui(){ document.location.href="${pageContext.request.contextPath}/CompanyManager"; }
script> <body > <div id="p" class="easyui-panel" title="设置企业Logo" style="width:auto;height:auto;padding:10px;fit:true;background:#fafafa;" data-options="iconCls:'icon-edit',closable:false, collapsible:false,minimizable:false,maximizable:false"> <center> <form name="form" action="<%=basePath%>uploadHeadImage" method="post" enctype="multipart/form-data"> <div class="modal-body text-center" style="height:auto"> <div class="zxx_main_con"> <div class="zxx_test_list"> <input class="photo-file" type="file" name="imgFile" id="imgFile" onchange="readURL(this);"> <button id="submit" class="easyui-linkbutton" style="width: 90px;">上传图片button> <a onclick="fanhui()" class="easyui-linkbutton" style="width: 90px;">返回a> <br /> <br /> <div id="result">div> <img alt="" src="" id="cutimg"/> div> div> div> <div style="margin-left: 15px"> <div style="font-weight: bold;">企业LOGO:div> <img id="testLogo" class="double-border" alt="" src="<%=request.getContextPath()%>/LoadcompanyLogo"> div> <div id="preview-pane"> <div class="preview-container"> <img id="cutimgPreview" src="" class="jcrop-preview" /> <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" /> div> div> <input type="hidden" name="message" value="<%=request.getAttribute("message") %>"> form> center> div> body>

点击企业logo,跳转到企业logo设置界面

JQuery 图像裁剪插件Jcrop实现图片上传功能(mysql DB)_第1张图片

上传图片
JQuery 图像裁剪插件Jcrop实现图片上传功能(mysql DB)_第2张图片

  • controller上传动作
 @RequestMapping(value = "/uploadHeadImage")
  public ModelAndView uploadHeadImage(
          HttpServletRequest request,HttpServletResponse response,
          @RequestParam(value = "x") String x,
          @RequestParam(value = "y") String y,
          @RequestParam(value = "h") String h,
          @RequestParam(value = "w") String w,
          @RequestParam(value = "imgFile",required = false) MultipartFile imageFile
  ) throws Exception{

      String databaseName = (String) request.getSession().getAttribute(
                CloudContext.DatabaseName)+"_authority";

      String realPath = request.getSession().getServletContext().getRealPath("/");
      String resourcePath = "resources/uploadImages/";
      if(imageFile!=null){
          if(FileUploadUtil.allowUpload(imageFile.getContentType())){
              String fileName = FileUploadUtil.rename(imageFile.getOriginalFilename());
              int end = fileName.lastIndexOf(".");
              String saveName = fileName.substring(0,end);
              File dir = new File(realPath + resourcePath);
              if(!dir.exists()){
                  dir.mkdirs();
              }
              File file = new File(dir,saveName+"_src.jpg");
              imageFile.transferTo(file);
              String srcImagePath = realPath + resourcePath + saveName;
              int imageX = ProcessString(x);         
              int imageY = ProcessString(y);
              int imageH = ProcessString(h);
              int imageW = ProcessString(w);
              //这里开始截取操作

              BufferedImage tag= ImageCut.imgCut(srcImagePath,imageX,imageY,imageW,imageH);

              FileInputStream inputStreamResult=getImageByte(srcImagePath+"_cut.jpg");
              //获取企业号-zhouzhou
              String companyId=(String) request.getSession().getAttribute(
                    CloudContext.DatabaseName);
              //企业数据库
              String dataBaseName=(String) request.getSession().getAttribute(
                        CloudContext.DatabaseName)+"_authority";
              companyLogo= companyBean.getCompanyInfoInfoBycompanyId(companyId,databaseName);
              byte[] photo = new byte[inputStreamResult.available()];

              inputStreamResult.read(photo);
              inputStreamResult.close();

              companyLogo.setCompanyLogo(photo);  
              companyLogo.setDataBaseName(dataBaseName);
              companyBean.updateEntity(companyLogo);
          }
      }
      return new ModelAndView("companyLogo");
  }

获取图片位置

private int ProcessString(String y)
  {
      int result;
      int is=y.indexOf(".");
        if (is==-1) {
        //没有点的时候
            result = Integer.parseInt(y);
        }else {
            //有点
            result =Integer.valueOf(y.substring(0,y.indexOf(".")));
        }
        return result;
  }

在公司首页显示logo
JQuery 图像裁剪插件Jcrop实现图片上传功能(mysql DB)_第3张图片

定义一个输出流,从mysql中查出内容,获取图片。DB中的字段为mediumblob类型,BLOB是一个二进制大型对象,是一个可以存储大量数据的容器,它能容纳不同大小的数据。mediumblob最多16M。


    /**
      * 查询企业logo
      *
      * @author zhouzhou
      * @version 5.0 , 2016年9月19日19:17:59
      * @param company
      * @param request
      * @param response
      */
      @RequestMapping(value="/LoadcompanyLogo")
      public void LoadCompanyLogo(Company company,HttpServletRequest request,HttpServletResponse response) {
          //获取数据库名称-zhouzhou
        String databaseName = (String) request.getSession().getAttribute(
                    CloudContext.DatabaseName)+"_authority";
        Company companyLogo;
        OutputStream os;
        try {
            os = response.getOutputStream();//定义一个输出流
            //获取企业号-zhouzhou
              company.setNumber((String) request.getSession().getAttribute(
                        CloudContext.DatabaseName));
              companyLogo= startHomeBean.getCompanyInfoInfoBycompanyId(company.getNumber(),databaseName);
              if (company!=null)
              {
                  byte [] yingjie= companyLogo.getCompanyLogo();
                  if(yingjie!=null && yingjie.length>0)
                  {
                      os.write(yingjie);                 

                  }else {

                }
                  os.flush();  
                  os.close();             
              }

        } catch (IOException e) {

            e.printStackTrace();
        }     

      }

总结

通过这个功能的开发,知道了mysql如何去储存图片,如何用JQ插件裁剪图片。之前只知道mongodb,FastDFS可以存储,后来才知道其实技术定位是根据需求而来了。单独存储几个小图片,还是用mysql就好。
要知道在什么需求下,使用什么技术。这才是一个合格的开发。

你可能感兴趣的:(3.ITOO)