当前位置: 澳门新濠3559 > 编程 > 正文

需要用到头像上传的功能,前端页面设计

时间:2019-11-21 05:33来源:编程
最近在做php第二阶段的项目,需要用到头像上传的功能 java web 网站头像上传处理 (springmvc +bootstrap+cropper) 制作头像上传。请根据您的实际需求,修改代码,不完全正确,仅供参考! 前端

最近在做php第二阶段的项目,需要用到头像上传的功能

java web 网站头像上传处理 (springmvc +bootstrap+cropper)

制作头像上传。请根据您的实际需求,修改代码,不完全正确,仅供参考!

前端页面设计使用bootstrap ,头像预览和剪裁工具使用cropper

后台使用springmvc。

现在来看前端的页面设计

前端页面设计,自然需要bootstrap 、jqury 和cropper ,这可以自行去网上百度查找

剪裁效果图

图片 1

html 文件  

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>cropper</title>
    <link href="css/bootstrap.css" rel="stylesheet"/>
    <link href="js/plugins/cropper/cropper.css" rel="stylesheet"/>
    <link href="css/style.css" rel="stylesheet"/>

</head>
<body>
<div class="container" id="crop-avatar">

    <!-- Current avatar -->
    <div style="text-align:center;color:red;margin:50px 0">提示:点击头像上传</div>
    <div class="avatar-view" title="Change the avatar">
        <img src="images/snow.jpg" alt="Avatar"/>
    </div>

    <!-- Cropping modal -->
    <div class="modal fade" id="avatar-modal" aria-hidden="true" aria-labelledby="avatar-modal-label" role="dialog" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <form class="avatar-form" action="crop.php" enctype="multipart/form-data" method="post">
                    <div class="modal-header">
                        <button class="close" data-dismiss="modal" type="button">×</button>
                        <h4 class="modal-title" id="avatar-modal-label">更换头像</h4>
                    </div>
                    <div class="modal-body">
                        <div class="avatar-body">

                            <!-- Upload image and data -->
                            <div class="avatar-upload">
                                <input class="avatar-src" name="avatar_src" type="hidden"/>
                                <input class="avatar-data" name="avatar_data" type="hidden"/>
                                <label for="avatarInput">头像上传</label>
                                <input class="avatar-input " id="avatarInput" name="avatar_file" type="file" accept="image/*"/>
                            </div>

                            <!-- Crop and preview -->
                            <div class="row">
                                <div class="col-md-9">
                                    <div class="avatar-wrapper"></div>
                                </div>
                                <div class="col-md-3">
                                    <!--<div class="avatar-preview preview-lg"></div>-->
                                    <div class="avatar-preview preview-md">
                                        <label>100*100</label>
                                    </div>
                                    <div class="avatar-preview preview-sm" title="50*50">
                                        <label>50*50</label>
                                    </div>
                                    <div class="avatar-preview preview-xs">
                                        <label>30*30</label>
                                    </div>
                                    <div class="input-group input-group-sm">
                                        <label class="input-group-addon" for="dataX">X</label>
                                        <input type="text" class="form-control" id="dataX" name="x" placeholder="x" >
                                        px
                                    </div>
                                    <div class="input-group input-group-sm">
                                        <label class="input-group-addon" for="dataY">Y</label>
                                        <input type="text" class="form-control" id="dataY" name="y" placeholder="y">
                                        px
                                    </div>
                                    <div class="input-group input-group-sm">
                                        <label class="input-group-addon" for="dataWidth">Width</label>
                                        <input type="text" class="form-control" id="dataWidth" name="width" placeholder="width">
                                        px
                                    </div>
                                    <div class="input-group input-group-sm">
                                        <label class="input-group-addon" for="dataHeight">Height</label>
                                        <input type="text" class="form-control" id="dataHeight" name="height" placeholder="height">
                                        px
                                    </div>
                                    <div class="input-group input-group-sm">
                                        <label class="input-group-addon" for="dataRotate">Rotate</label>
                                        <input type="text" class="form-control" id="dataRotate" placeholder="rotate">
                                        deg
                                    </div>
                                    <div class="input-group input-group-sm">
                                        <label class="input-group-addon" for="dataScaleX">ScaleX</label>
                                        <input type="text" class="form-control" id="dataScaleX" placeholder="scaleX">
                                    </div>
                                    <div class="input-group input-group-sm">
                                        <label class="input-group-addon" for="dataScaleY">ScaleY</label>
                                        <input type="text" class="form-control" id="dataScaleY" placeholder="scaleY">
                                    </div>
                                </div>
                            </div>

                            <div class="row avatar-btns">
                                <div class="col-md-9">
                                    <div class="btn-group">
                                        <button class="btn btn-primary" data-method="rotate" data-option="-90" type="button" title="Rotate -90 degrees">向左旋转</button>
                                        <button class="btn btn-primary" data-method="rotate" data-option="-15" type="button">-15deg</button>
                                        <button class="btn btn-primary" data-method="rotate" data-option="-30" type="button">-30deg</button>
                                        <button class="btn btn-primary" data-method="rotate" data-option="-45" type="button">-45deg</button>
                                    </div>
                                    <div class="btn-group">
                                        <button class="btn btn-primary" data-method="rotate" data-option="90" type="button" title="Rotate 90 degrees">向右旋转</button>
                                        <button class="btn btn-primary" data-method="rotate" data-option="15" type="button">15deg</button>
                                        <button class="btn btn-primary" data-method="rotate" data-option="30" type="button">30deg</button>
                                        <button class="btn btn-primary" data-method="rotate" data-option="45" type="button">45deg</button>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <button class="btn btn-primary btn-block avatar-save" type="submit">确定</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- <div class="modal-footer">
                      <button class="btn btn-default" data-dismiss="modal" type="button">Close</button>
                    </div> -->
                </form>
            </div>
        </div>
    </div><!-- /.modal -->

    <!-- Loading state -->
    <div class="loading" aria-label="Loading" role="img" tabindex="-1"></div>
</div>

<script src="js/jquery-2.1.4.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/plugins/cropper/cropper.min.js"></script>
<script src="js/cropper-tool.js"></script>
</body>
</html>

js处理文件如下

main,js

$(function () {

  'use strict';

  var console = window.console || { log: function () {} };
  var $image = $('#image');
  var $download = $('#download');
  var $dataX = $('#dataX');
  var $dataY = $('#dataY');
  var $dataHeight = $('#dataHeight');
  var $dataWidth = $('#dataWidth');
  var $dataRotate = $('#dataRotate');
  var $dataScaleX = $('#dataScaleX');
  var $dataScaleY = $('#dataScaleY');
  var options = {
        aspectRatio: 16 / 9,
        preview: '.img-preview',
        crop: function (e) {
          $dataX.val(Math.round(e.x));
          $dataY.val(Math.round(e.y));
          $dataHeight.val(Math.round(e.height));
          $dataWidth.val(Math.round(e.width));
          $dataRotate.val(e.rotate);
          $dataScaleX.val(e.scaleX);
          $dataScaleY.val(e.scaleY);
        }
      };


  // Tooltip
  $('[data-toggle="tooltip"]').tooltip();


  // Cropper
  $image.on({
    'build.cropper': function (e) {
      console.log(e.type);
    },
    'built.cropper': function (e) {
      console.log(e.type);
    },
    'cropstart.cropper': function (e) {
      console.log(e.type, e.action);
    },
    'cropmove.cropper': function (e) {
      console.log(e.type, e.action);
    },
    'cropend.cropper': function (e) {
      console.log(e.type, e.action);
    },
    'crop.cropper': function (e) {
      console.log(e.type, e.x, e.y, e.width, e.height, e.rotate, e.scaleX, e.scaleY);
    },
    'zoom.cropper': function (e) {
      console.log(e.type, e.ratio);
    }
  }).cropper(options);


  // Buttons
  if (!$.isFunction(document.createElement('canvas').getContext)) {
    $('button[data-method="getCroppedCanvas"]').prop('disabled', true);
  }

  if (typeof document.createElement('cropper').style.transition === 'undefined') {
    $('button[data-method="rotate"]').prop('disabled', true);
    $('button[data-method="scale"]').prop('disabled', true);
  }


  // Download
  if (typeof $download[0].download === 'undefined') {
    $download.addClass('disabled');
  }


  // Options
  $('.docs-toggles').on('change', 'input', function () {
    var $this = $(this);
    var name = $this.attr('name');
    var type = $this.prop('type');
    var cropBoxData;
    var canvasData;

    if (!$image.data('cropper')) {
      return;
    }

    if (type === 'checkbox') {
      options[name] = $this.prop('checked');
      cropBoxData = $image.cropper('getCropBoxData');
      canvasData = $image.cropper('getCanvasData');

      options.built = function () {
        $image.cropper('setCropBoxData', cropBoxData);
        $image.cropper('setCanvasData', canvasData);
      };
    } else if (type === 'radio') {
      options[name] = $this.val();
    }

    $image.cropper('destroy').cropper(options);
  });


  // Methods
  $('.docs-buttons').on('click', '[data-method]', function () {
    var $this = $(this);
    var data = $this.data();
    var $target;
    var result;

    if ($this.prop('disabled') || $this.hasClass('disabled')) {
      return;
    }

    if ($image.data('cropper') && data.method) {
      data = $.extend({}, data); // Clone a new one

      if (typeof data.target !== 'undefined') {
        $target = $(data.target);

        if (typeof data.option === 'undefined') {
          try {
            data.option = JSON.parse($target.val());
          } catch (e) {
            console.log(e.message);
          }
        }
      }

      result = $image.cropper(data.method, data.option, data.secondOption);

      switch (data.method) {
        case 'scaleX':
        case 'scaleY':
          $(this).data('option', -data.option);
          break;

        case 'getCroppedCanvas':
          if (result) {

            // Bootstrap's Modal
            $('#getCroppedCanvasModal').modal().find('.modal-body').html(result);

            if (!$download.hasClass('disabled')) {
              $download.attr('href', result.toDataURL('image/jpeg'));
            }
          }

          break;
      }

      if ($.isPlainObject(result) && $target) {
        try {
          $target.val(JSON.stringify(result));
        } catch (e) {
          console.log(e.message);
        }
      }

    }
  });


  // Keyboard
  $(document.body).on('keydown', function (e) {

    if (!$image.data('cropper') || this.scrollTop > 300) {
      return;
    }

    switch (e.which) {
      case 37:
        e.preventDefault();
        $image.cropper('move', -1, 0);
        break;

      case 38:
        e.preventDefault();
        $image.cropper('move', 0, -1);
        break;

      case 39:
        e.preventDefault();
        $image.cropper('move', 1, 0);
        break;

      case 40:
        e.preventDefault();
        $image.cropper('move', 0, 1);
        break;
    }

  });


  // Import image
  var $inputImage = $('#inputImage');
  var URL = window.URL || window.webkitURL;
  var blobURL;

  if (URL) {
    $inputImage.change(function () {
      var files = this.files;
      var file;

      if (!$image.data('cropper')) {
        return;
      }

      if (files && files.length) {
        file = files[0];

        if (/^image/w+$/.test(file.type)) {
          blobURL = URL.createObjectURL(file);
          $image.one('built.cropper', function () {

            // Revoke when load complete
            URL.revokeObjectURL(blobURL);
          }).cropper('reset').cropper('replace', blobURL);
          $inputImage.val('');
        } else {
          window.alert('Please choose an image file.');
        }
      }
    });
  } else {
    $inputImage.prop('disabled', true).parent().addClass('disabled');
  }

});

需要添加的css样式

 

style.css

 

.avatar-view {
    display: block;
    margin: 0 auto;
    height: 220px;
    width: 220px;
    border: 3px solid #fff;
    border-radius: 5px;
    box-shadow: 0 0 5px rgba(0,0,0,.15);
    cursor: pointer;
    overflow: hidden;
}

.avatar-view img {
    width: 100%;
}

.avatar-body {
    padding-right: 15px;
    padding-left: 15px;
}

.avatar-upload {
    overflow: hidden;
}

.avatar-upload label {
    display: block;
    float: left;
    clear: left;
    width: 100px;
}

.avatar-upload input {
    display: block;
    margin-left: 110px;
}

.avater-alert {
    margin-top: 10px;
    margin-bottom: 10px;
}

.avatar-wrapper {
    height: 364px;
    width: 100%;
    margin-top: 15px;
    box-shadow: inset 0 0 5px rgba(0,0,0,.25);
    background-color: #fcfcfc;
    overflow: hidden;
}

.avatar-wrapper img {
    display: block;
    height: auto;
    max-width: 100%;
}

.avatar-preview {
    float: left;
    margin-top: 15px;
    margin-right: 15px;
    border: 1px solid #eee;
    border-radius: 4px;
    background-color: #fff;
    overflow: hidden;
}

.avatar-preview:hover {
    border-color: #ccf;
    box-shadow: 0 0 5px rgba(0,0,0,.15);
}

.avatar-preview img {
    width: 100%;
}

.preview-lg {
    height: 200px;
    width: 200px;
    margin-top: 15px;
}

.preview-md {
    height: 100px;
    width: 100px;
}

.preview-sm {
    height: 50px;
    width: 50px;
}
.preview-xs{
    height:30px;
    width:30px;]
}

@media (min-width: 992px) {
    .avatar-preview {
        float: none;
    }
}

.avatar-btns {
    margin-top: 30px;
    margin-bottom: 15px;
}

.avatar-btns .btn-group {
    margin-right: 5px;
}

.loading {
    display: none;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: #fff url("patterns/loading.gif") no-repeat center center;
    opacity: .75;
    filter: alpha(opacity=75);
    z-index: 20140628;
}

现在前端的基本完成。现在最重要的来了,就是后台java 处理了。在网上找过很多,发现没有,关于springmvc的,上面的内容基本上在网上找到,下面的springmvc的,关于图像处理的,就是我个人做的。好像网上有直接在前端进行剪裁的,可惜我不会啊,所以我还是老老实实的在后台处理了。

 

 

package com.cx.wxs.action.image;

import java.io.File;
import java.sql.Timestamp;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cx.wxs.dto.BSiteDto;
import com.cx.wxs.dto.IAlbumDto;
import com.cx.wxs.dto.IImageDto;
import com.cx.wxs.dto.UUserDto;
import com.cx.wxs.service.BSiteService;
import com.cx.wxs.service.IImageService;
import com.cx.wxs.service.UUserService;
import com.cx.wxs.utils.DateUtils;
import com.cx.wxs.utils.clientInfo;
import com.cx.wxs.utils.imageUtils;

/**
 * @author roychenyi
 * @date   2016-3-29 下午9:22:01
 */
@Controller
@RequestMapping("/{vip}/image")
public class imageAction {

 @Resource
 private IImageService iImageService;
 @Resource
 private BSiteService bSiteService;
 @Resource
 private UUserService uUserService;

 /**
  * @return the bSiteService
  */
 public BSiteService getbSiteService() {
  return bSiteService;
 }

 /**
  * @param bSiteService the bSiteService to set
  */
 public void setbSiteService(BSiteService bSiteService) {
  this.bSiteService = bSiteService;
 }

 /**
  * @return the uUserService
  */
 public UUserService getuUserService() {
  return uUserService;
 }

 /**
  * @param uUserService the uUserService to set
  */
 public void setuUserService(UUserService uUserService) {
  this.uUserService = uUserService;
 }

 /**
  * @return the iImageService
  */
 public IImageService getiImageService() {
  return iImageService;
 }

 /**
  * @param iImageService the iImageService to set
  */
 public void setiImageService(IImageService iImageService) {
  this.iImageService = iImageService;
 }
 @RequestMapping(value="/updateuserlogo")
 @ResponseBody
 public IImageDto updateUserLogo( @PathVariable("vip") String vip,
    Integer x, Integer y, Integer width, Integer height,Integer degree,
   @RequestParam(value = "avatar_file") MultipartFile imageFile, HttpServletRequest request,HttpServletResponse response){
  IImageDto imageDto=new IImageDto();
  //获取服务器的实际路径
   String realPath = request.getSession().getServletContext().getRealPath("/");
     System.out.println("x:"+x+"y:"+y+"width:"+width+"height:"+height+"degree:"+degree);
  System.out.println(realPath);
  //需要上传的路径,我的路径根据用户的和当前日期划分路径
  String resourcePath="upload/image";
  UUserDto userDto=(UUserDto) request.getSession().getAttribute("user");
  resourcePath+="/"+userDto.getUserId();

   if(imageFile!=null){
    try{
   //文件名
    String name= imageFile.getOriginalFilename();
    //获取时间的路径
    Date date=new Date();    
    int year=DateUtils.getYear(date);
    int month=DateUtils.getMonth(date);
    int day=DateUtils.getDay(date);
    resourcePath+="/"+year+"/"+month+"/"+day+"/";
    File dir=new File(realPath+resourcePath);
    if(!dir.exists()){
     dir.mkdirs();
    }
    //先把用户上传到原图保存到服务器上
    File file=new File(dir,date.getTime()+".jpg");
    imageFile.transferTo(file);
    if(file.exists()){
     String src=realPath+resourcePath+date.getTime();

     boolean[] flag=new boolean[6];
     //旋转后剪裁图片
     flag[0]=imageUtils.cutAndRotateImage(src+".jpg", src+"_s.jpg", x, y, width, height, degree);
     //缩放图片,生成不同大小的图片,应用于不同的大小的头像显示
     flag[1]= imageUtils.scale2(src+"_s.jpg", src+"_s_200.jpg", 200, 200, true);
     flag[2]= imageUtils.scale2(src+"_s.jpg", src+"_s_100.jpg", 100, 100, true);
     flag[3]= imageUtils.scale2(src+"_s.jpg", src+"_s_50.jpg", 50, 50, true);
     flag[4]= imageUtils.scale2(src+"_s.jpg", src+"_s_30.jpg", 30, 30, true);
     flag[5]= imageUtils.scale2(file.getPath(), src+"_200.jpg", 200, 200, true);

     if(flag[0]&&flag[1]&&flag[2]&&flag[3]&&flag[4]&&flag[5]){
      //图像处理完成,将数据写入数据库中
      imageDto.setYear((short) year);
      imageDto.setMount((short)month);
      imageDto.setDay((short)day);
      imageDto.setUUserDto(userDto);
      imageDto.setName(date.getTime()+".jpg");
      imageDto.setFileName(name);
      imageDto.setUrl(resourcePath+"/"+date.getTime()+".jpg");
      imageDto.setPreviewUrl(resourcePath+"/"+date.getTime()+"_200.jpg");
      imageDto.setTime(new Timestamp(date.getTime()));
      imageDto.setWidth((short)imageUtils.getImageWidth(file.getPath()));
      imageDto.setHeight((short)imageUtils.getImageHeight(file.getPath()));
      imageDto.setClientIp(clientInfo.getIpAddr(request));
      imageDto.setClientAgent(clientInfo.getAgent(request));
      imageDto.setClientType((short)(clientInfo.isMoblie(request)?1:0));
      imageDto.setStatus((short)1);
      imageDto.setExt3(resourcePath+"/"+date.getTime()+"_s_200.jpg");
      imageDto.setExt4(resourcePath+"/"+date.getTime()+"_s_100.jpg");
     //设置相册,头像设置进入默认相册
      IAlbumDto albumDto=new IAlbumDto();
      albumDto.setAlbumId(1);
      imageDto.setIAlbumDto(albumDto);
      int id= iImageService.addIImage(imageDto);
      if(id>0){
       BSiteDto siteDto=userDto.getBSiteDto();
       siteDto.setLogo(resourcePath+"/"+date.getTime()+"_s_100.jpg");
       siteDto.setLastTime( new Timestamp(date.getTime()));
       bSiteService.updateBSite(siteDto);
       userDto.setPortrait(resourcePath+"/"+date.getTime()+"_s_30.jpg");
       uUserService.updateUuser(userDto);
       userDto=uUserService.getUuser(userDto);
       imageDto.setLoginFlag("1");
       return imageDto;
      }
     }
    }
    }catch (Exception e) {
    // TODO: handle exception
     e.printStackTrace();
     return imageDto;
   }

   }
  return imageDto;
 }
}

 

下面是图像处理的工具类。imageUtils.java.欢迎借鉴引用。(我也是在我网上找了很多进行参考的)

 

package com.cx.wxs.utils;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.cx.wxs.dto.IImageDto;


/**
 * @author roychenyi
 * @date   2016-3-30 上午10:11:39
 */
public class imageUtils {
 private static Log log = LogFactory.getLog(imageUtils.class);


 /***
  * 获取图片的类型
  * @param o
  * @return
  * @date   2016-3-30下午4:59:36
  */
 private static String getFormatName(Object o) {
        try {
            ImageInputStream iis = ImageIO.createImageInputStream(o);
            Iterator iter = ImageIO.getImageReaders(iis);
            if (!iter.hasNext()) {
                return null;
            }

            ImageReader reader = iter.next();
            iis.close();
            return reader.getFormatName();
        } catch (IOException e) {
        }
        return null;
    }

 /**
     * 使用ImageReader获取图片尺寸
     * 
     * @param src
     *            源图片路径
     */
    public void getImageSizeByImageReader(String src) {
        long beginTime = new Date().getTime();
        File file = new File(src);
        try {
            Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
            ImageReader reader = (ImageReader) readers.next();
            ImageInputStream iis = ImageIO.createImageInputStream(file);
            reader.setInput(iis, true);
            System.out.println("width:" + reader.getWidth(0));
            System.out.println("height:" + reader.getHeight(0));
        } catch (IOException e) {
            e.printStackTrace();
        }
        long endTime = new Date().getTime();
        System.out.println("使用[ImageReader]获取图片尺寸耗时:[" + (endTime - beginTime)+"]ms");
    }

    /**
     * 使用BufferedImage获取图片尺寸
     * 
     * @param src
     *            源图片路径
     */
    public void getImageSizeByBufferedImage(String src) {
        long beginTime = new Date().getTime();
        File file = new File(src);
        FileInputStream is = null;
        try {
            is = new FileInputStream(file);
        } catch (FileNotFoundException e2) {
            e2.printStackTrace();
        }
        BufferedImage sourceImg = null;
        try {
            sourceImg = javax.imageio.ImageIO.read(is);
            System.out.println("width:" + sourceImg.getWidth());
            System.out.println("height:" + sourceImg.getHeight());
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        long endTime = new Date().getTime();
        System.out.println("使用[BufferedImage]获取图片尺寸耗时:[" + (endTime - beginTime)+"]ms");
    }

    /***
     * 获取图片的宽
     * @param srcImageFile
     * @return
     * @date   2016-3-30下午9:01:08
     */
    public static int  getImageWidth(String srcImageFile){
         try {
          File file = new File(srcImageFile);
             Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
             ImageReader reader = (ImageReader) readers.next();
             ImageInputStream iis = ImageIO.createImageInputStream(file);
             reader.setInput(iis, true);

             return reader.getWidth(0);
         } catch (IOException e) {
             e.printStackTrace();
             return 0;
         }
    }
    /***
     * 获取文件的高
     * @param srcImageFile
     * @return
     * @date   2016-3-30下午9:02:19
     */
    public static int getImageHeight(String srcImageFile){
     File file = new File(srcImageFile);
        try {
            Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
            ImageReader reader = (ImageReader) readers.next();
            ImageInputStream iis = ImageIO.createImageInputStream(file);
            reader.setInput(iis, true);

            return reader.getHeight(0);
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }
    }

 /***
  * 剪裁图片
  * @param src
  * @param dest
  * @param x  起点横坐标
  * @param y  纵坐标
  * @param w  长
  * @param h  高
  * @throws IOException
  * @date   2016-3-30下午12:19:10
  */
  public static boolean cutImage(String src,String dest,int x,int y,int w,int h) {   
         try{
   Iterator iterator = ImageIO.getImageReadersByFormatName("jpg");   
         ImageReader reader = (ImageReader)iterator.next();   
         InputStream in=new FileInputStream(src);  
         ImageInputStream iis = ImageIO.createImageInputStream(in);   
         reader.setInput(iis, true);   
         ImageReadParam param = reader.getDefaultReadParam(); 
         x=(x>0?x:0);
         y=(y>0?y:0);
         Rectangle rect = new Rectangle(x, y, w,h);    
         param.setSourceRegion(rect);   
         BufferedImage bi = reader.read(0,param);     
         ImageIO.write(bi, "jpg", new File(dest));    
         return true;
         }catch (Exception e) {
   // TODO: handle exception
          e.printStackTrace();
          return false;
  }

  } 
  /***
   * 图片旋转指定角度
   * @param bufferedimage 图像
   * @param degree      角度
   * @return
   * @date   2016-3-30下午3:10:27
   */
  public static BufferedImage rotateImage(final BufferedImage bufferedimage,
             final int degree) {
         int w = bufferedimage.getWidth();
         int h = bufferedimage.getHeight();
         int type = bufferedimage.getColorModel().getTransparency();
         BufferedImage img;
         Graphics2D graphics2d;
         (graphics2d = (img = new BufferedImage(w, h, type))
                 .createGraphics()).setRenderingHint(
                 RenderingHints.KEY_INTERPOLATION,
                 RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    //     graphics2d.setBackground(Color.white);
         graphics2d.setPaint(Color.WHITE);
         graphics2d.fillRect(0, 0, w, h);
         graphics2d.rotate(Math.toRadians(degree), w / 2, h / 2);
         graphics2d.drawImage(bufferedimage, 0, 0,Color.WHITE, null);
         graphics2d.dispose();
         return img;
     }
  public static boolean rotateImage(String srcImageFile, String result,
    int degree){
   try{
    BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件
    BufferedImage tag= rotateImage(src, degree);

    ImageIO.write(tag, "JPEG", new File(result));

    return true;
   }catch (Exception e) {
    // TODO: handle exception
    return false;
   }
  }

  public static BufferedImage Rotate(Image src, int angel) {  
         int src_width = src.getWidth(null);  
         int src_height = src.getHeight(null); 
       //  angel=angel>0?angel:(360-angel);
         // calculate the new image size  
         Rectangle rect_des = CalcRotatedSize(new Rectangle(new Dimension(  
                 src_width, src_height)), angel);  

         BufferedImage res = null;  
         res = new BufferedImage(rect_des.width, rect_des.height,  
                 BufferedImage.TYPE_INT_RGB);  
         Graphics2D g2 = res.createGraphics();  
         g2.setPaint(Color.WHITE);
         g2.fillRect(0, 0, rect_des.width,  rect_des.height);
         // transform  
         g2.translate((rect_des.width - src_width) / 2,  
                 (rect_des.height - src_height) / 2);  
         g2.rotate(Math.toRadians(angel), src_width / 2, src_height / 2);  

         g2.drawImage(src, null, null);  
         return res;  
     }  

     public static Rectangle CalcRotatedSize(Rectangle src, int angel) {  
         // if angel is greater than 90 degree, we need to do some conversion  
         if (angel >= 90) {  
             if(angel / 90 % 2 == 1){  
                 int temp = src.height;  
                 src.height = src.width;  
                 src.width = temp;  
             }  
             angel = angel % 90;  
         }  

         double r = Math.sqrt(src.height * src.height + src.width * src.width) / 2;  
         double len = 2 * Math.sin(Math.toRadians(angel) / 2) * r;  
         double angel_alpha = (Math.PI - Math.toRadians(angel)) / 2;  
         double angel_dalta_width = Math.atan((double) src.height / src.width);  
         double angel_dalta_height = Math.atan((double) src.width / src.height);  

         int len_dalta_width = (int) (len * Math.cos(Math.PI - angel_alpha  
                 - angel_dalta_width));  
         int len_dalta_height = (int) (len * Math.cos(Math.PI - angel_alpha  
                 - angel_dalta_height));  
         int des_width = src.width + len_dalta_width * 2;  
         int des_height = src.height + len_dalta_height * 2;  
         return new java.awt.Rectangle(new Dimension(des_width, des_height));  
     }

     public static boolean Rotate(String srcImageFile, String result,
             int degree){
      try{
       degree=degree>0?degree:(360-degree);
       BufferedImage src = ImageIO.read(new File(srcImageFile));  
             BufferedImage tag = Rotate(src, degree);
             ImageIO.write(tag, "JPEG", new File(result));     
     return true;
      }catch (Exception e) {
    // TODO: handle exception
       e.printStackTrace();
       return false;
   }
     }


 public static boolean cutAndRotateImage(String srcImageFile,String dest,int x,int y,int w,int h,int degree){
  try{
   BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件
   BufferedImage tag= Rotate(src, degree);
    Iterator iterator = ImageIO.getImageReadersByFormatName("jpg");   
          ImageReader reader = (ImageReader)iterator.next();   
     //     InputStream in=new FileInputStream(tag); 
          ByteArrayOutputStream bs = new ByteArrayOutputStream();  
          ImageOutputStream ios = ImageIO.createImageOutputStream(bs);  
          ImageIO.write(tag, "jpg", ios);
          InputStream in=new  ByteArrayInputStream(bs.toByteArray());
          ImageInputStream iis=ImageIO.createImageInputStream(in);
          reader.setInput(iis, true);   
          ImageReadParam param = reader.getDefaultReadParam(); 
          x=(x>0?x:0);
          y=(y>0?y:0);
          Rectangle rect = new Rectangle(x, y, w,h);    
          param.setSourceRegion(rect);   
          BufferedImage bi = reader.read(0,param);     
          ImageIO.write(bi, "jpg", new File(dest));  
   return true;
  }catch (Exception e) {
   // TODO: handle exception
   return false;
  }
 }

  /***
   * 按照比例缩放
   * @param srcImageFile
   * @param result  
   * @param scale 缩放比例
   * @param flag 缩放选择:true 放大; false 缩小;
   * @return
   * @date   2016-3-30下午2:39:44
   */
  public  static boolean scale(String srcImageFile, String result,
             int scale, boolean flag) {
         try {
          File file = new File(srcImageFile);
             BufferedImage src = ImageIO.read(file); // 读入文件
              Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
              ImageReader reader = (ImageReader) readers.next();
              ImageInputStream iis = ImageIO.createImageInputStream(file);
              reader.setInput(iis, true);
             int width = reader.getWidth(0); // 得到源图宽
             int height = reader.getHeight(0); // 得到源图长
             if (flag) {// 放大
                 width = width * scale;
                 height = height * scale;
             } else {// 缩小
                 width = width / scale;
                 height = height / scale;
             }
             Image image = src.getScaledInstance(width, height,
                     Image.SCALE_DEFAULT);
             BufferedImage tag = new BufferedImage(width, height,
                     BufferedImage.TYPE_INT_RGB);
             Graphics g = tag.getGraphics();
             g.drawImage(image, 0, 0, null); // 绘制缩小后的图
             g.dispose();
             ImageIO.write(tag, "jpg", new File(result));// 输出到文件流
             return true;
         } catch (IOException e) {
             e.printStackTrace();
             return false;
         }
     }
  /***
   * 缩放图像,按照长宽缩放
   * @param srcImageFile
   * @param result
   * @param height  变换后的高度
   * @param width   变换后的长度
   * @param bb      比例不对称时,是否补白,true 补白;false 不补白
   * @return

   * @date   2016-3-30下午2:44:37
   */
  public  static boolean scale2(String srcImageFile, String result, int height, int width, boolean bb) {
         try {
             double ratio = 0.0; // 缩放比例
             File file = new File(srcImageFile);
             BufferedImage bi = ImageIO.read(file); // 读入文件
              Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
              ImageReader reader = (ImageReader) readers.next();
              ImageInputStream iis = ImageIO.createImageInputStream(file);
              reader.setInput(iis, true);
             int width1 = reader.getWidth(0); // 得到源图宽
             int height1 = reader.getHeight(0); // 得到源图长
             Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);
             // 计算比例
             if ((height1 > height) || (width1 > width)) {
                 if (height1 > width1) {
                     ratio = (new Integer(height)).doubleValue()
                             / height1;
                 } else {
                     ratio = (new Integer(width)).doubleValue() / width1;
                 }
                 AffineTransformOp op = new AffineTransformOp(AffineTransform
                         .getScaleInstance(ratio, ratio), null);
                 itemp = op.filter(bi, null);
             }
             if (bb) {//补白
                 BufferedImage image = new BufferedImage(width, height,
                         BufferedImage.TYPE_INT_RGB);
                 Graphics2D g = image.createGraphics();
                 g.setColor(Color.white);
                 g.fillRect(0, 0, width, height);
                 if (width == itemp.getWidth(null))
                     g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2,
                             itemp.getWidth(null), itemp.getHeight(null),
                             Color.white, null);
                 else
                     g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0,
                             itemp.getWidth(null), itemp.getHeight(null),
                             Color.white, null);
                 g.dispose();
                 itemp = image;
             }
             ImageIO.write((BufferedImage) itemp, "JPEG", new File(result));
             return true;
         } catch (IOException e) {
             e.printStackTrace();
             return false;
         }
     }
  /***
   * 转换图像格式
   * @param srcImageFile 原图像地址
   * @param formatName   转换类型
   * @param destImageFile 转换后的地址
   * @return
   * @author roychenyi
   * @date   2016-3-30下午2:49:15
   */
     public  static boolean convert(String srcImageFile, String formatName, String destImageFile) {
         try {
             File f = new File(srcImageFile);
             f.canRead();
             f.canWrite();
             BufferedImage src = ImageIO.read(f);
             ImageIO.write(src, formatName, new File(destImageFile));
             return true;
         } catch (Exception e) {
             e.printStackTrace();
             return false;
         }
     }

     /**
      * 彩色转为黑白 
      * @param srcImageFile 源图像地址
      * @param destImageFile 目标图像地址
      */
     public final static void gray(String srcImageFile, String destImageFile) {
         try {
             BufferedImage src = ImageIO.read(new File(srcImageFile));
             ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
             ColorConvertOp op = new ColorConvertOp(cs, null);
             src = op.filter(src, null);
             ImageIO.write(src, "jpg", new File(destImageFile));
         } catch (IOException e) {
             e.printStackTrace();
         }
     }

     /**
      * 给图片添加图片水印
      * @param pressImg 水印图片
      * @param srcImageFile 源图像地址
      * @param destImageFile 目标图像地址
      * @param x 修正值。 默认在中间
      * @param y 修正值。 默认在中间
      * @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字
      */
     public  static boolean pressImage(String pressImg, String srcImageFile,String destImageFile,
             int x, int y, float alpha) {
         try {
          File file = new File(srcImageFile);
             BufferedImage src = ImageIO.read(file); // 读入文件
              Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
              ImageReader reader = (ImageReader) readers.next();
              ImageInputStream iis = ImageIO.createImageInputStream(file);
              reader.setInput(iis, true);
             int width = reader.getWidth(0); // 得到源图宽
             int height = reader.getHeight(0); // 得到源图长
             BufferedImage image = new BufferedImage(width, height,
                     BufferedImage.TYPE_INT_RGB);
             Graphics2D g = image.createGraphics();
             g.drawImage(src, 0, 0, width, height, null);
             // 水印文件
             Image src_biao = ImageIO.read(new File(pressImg));
             int wideth_biao = src_biao.getWidth(null);
             int height_biao = src_biao.getHeight(null);
             g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                     alpha));
             g.drawImage(src_biao, (width-wideth_biao-x) ,
                     (height-height_biao-y) , wideth_biao, height_biao, null);
             // 水印文件结束
             g.dispose();
             ImageIO.write((BufferedImage) image,  "jpg", new File(destImageFile));
             return true;
         } catch (Exception e) {
             e.printStackTrace();
             return false;
         }
     }

     /**
      * 给图片添加文字水印
      * @param pressText 水印文字
      * @param srcImageFile 源图像地址
      * @param destImageFile 目标图像地址
      * @param fontName 水印的字体名称
      * @param fontStyle 水印的字体样式
      * @param color 水印的字体颜色
      * @param fontSize 水印的字体大小
      * @param x 修正值
      * @param y 修正值
      * @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字
      */
     public  static boolean pressText(String pressText,
             String srcImageFile, String destImageFile, String fontName,
             int fontStyle, Color color, int fontSize,int x,
             int y, float alpha) {
         try {
          File file = new File(srcImageFile);
             BufferedImage src = ImageIO.read(file); // 读入文件
              Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
              ImageReader reader = (ImageReader) readers.next();
              ImageInputStream iis = ImageIO.createImageInputStream(file);
              reader.setInput(iis, true);
             int width = reader.getWidth(0); // 得到源图宽
             int height = reader.getHeight(0); // 得到源图长
             BufferedImage image = new BufferedImage(width, height,
                     BufferedImage.TYPE_INT_RGB);
             Graphics2D g = image.createGraphics();
             g.drawImage(src, 0, 0, width, height, null);
             g.setColor(color);
             g.setFont(new Font(fontName, fontStyle, fontSize));
             g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                     alpha));
             // 在指定坐标绘制水印文字
             g.drawString(pressText, (width - (getLength(pressText) * fontSize))
                     / 2 + x, (height - fontSize) / 2 + y);
             g.dispose();
             ImageIO.write(image, "jpg", new File(destImageFile));// 输出到文件流
             return true;
         } catch (Exception e) {
             e.printStackTrace();
             return false;
         }
     }

     /**
      * 计算text的长度(一个中文算两个字符)
      * @param text
      * @return
      */
     public  static int getLength(String text) {
         int length = 0;
         for (int i = 0; i < text.length(); i++) {
             if (new String(text.charAt(i) + "").getBytes().length > 1) {
                 length += 2;
             } else {
                 length += 1;
             }
         }
         return length / 2;
     }


     public static void main(String[] args) {
  String src="D:/0.jpg";
  /*  imageUtils.cutImage(src, "D://1cut.jpg", -10, 40, 100000, 560);
  imageUtils.rotateImage(src, "D:/2rotate.jpg", -30);
  imageUtils.rotateImage(src, "D:/2rotate1.png", 30);
  imageUtils.Rotate(src, "D://2rotate2.jpg", 330);
  imageUtils.Rotate(src,"D://2rotate21.jpg",30);
  imageUtils.cutAndRotateImage(src, "D://9cutRotate1.jpg", 244, 427, 614, 614, 0);
  imageUtils.scale(src, "D://3scale1.jpg", 3, false);
  imageUtils.scale2(src, "D://4scale2.jpg", 780,560, false);
  imageUtils.convert(src, "png", "D://5convert.png");
  imageUtils.gray(src,"D://6gray.jpg");
  imageUtils.pressImage("D://3scale1.jpg", src, "D://7pressImage.jpg", 100, 100, 0.9f);
  imageUtils.pressText("图片1414", src, "D://8pressText.jpg", "宋体", Font.BOLD, Color.black, 80, 10, 10,0.6f);
*/
   imageUtils util = new imageUtils();
         util.getImageSizeByImageReader(src);
         util.getImageSizeByBufferedImage(src);
         System.out.println(getImageHeight(src));
         imageUtils.Rotate("E:\apache-tomcat-7.0.59\webapps\wxs\upload\image\1\2016\3\30\1459347622160.jpg","E:\apache-tomcat-7.0.59\webapps\wxs\upload/image/1/2016/3/30/1459347622160_s.jpg", 90);
         imageUtils.Rotate("E:/apache-tomcat-7.0.59/webapps/wxs/upload/image/1/2016/3/30/1459349306443_s.jpg", "E:/apache-tomcat-7.0.59/webapps/wxs/upload/image/1/2016/3/30/1459349306443_s_200.jpg", 45);
 }
}

 

制作头像上传。请根据您的实际需求,修改代码,不完全正确,仅供参考!

前端页面设计使用bootstrap ,头像预览和剪裁工具使用cropper

后台使用springmvc。

 

现在来看前端的页面设计

前端页面设计,自然需要bootstrap 、jqury 和cropper ,这可以自行去网上百度查找

剪裁效果图

 

html 文件

 

提示:点击头像上传

图片 2 <script src="js/jquery-2.1.4.min.js"></script><script src="js/bootstrap.min.js"></script><script src="js/plugins/cropper/cropper.min.js"></script><script src="js/cropper-tool.js"></script>

 

js处理文件如下

main,js

$(function () {

  'use strict';

  var console = window.console || { log: function () {} };
  var $image = $('#image');
  var $download = $('#download');
  var $dataX = $('#dataX');
  var $dataY = $('#dataY');
  var $dataHeight = $('#dataHeight');
  var $dataWidth = $('#dataWidth');
  var $dataRotate = $('#dataRotate');
  var $dataScaleX = $('#dataScaleX');
  var $dataScaleY = $('#dataScaleY');
  var options = {
        aspectRatio: 16 / 9,
        preview: '.img-preview',
        crop: function (e) {
          $dataX.val(Math.round(e.x));
          $dataY.val(Math.round(e.y));
          $dataHeight.val(Math.round(e.height));
          $dataWidth.val(Math.round(e.width));
          $dataRotate.val(e.rotate);
          $dataScaleX.val(e.scaleX);
          $dataScaleY.val(e.scaleY);
        }
      };


  // Tooltip
  $('[data-toggle="tooltip"]').tooltip();


  // Cropper
  $image.on({
    'build.cropper': function (e) {
      console.log(e.type);
    },
    'built.cropper': function (e) {
      console.log(e.type);
    },
    'cropstart.cropper': function (e) {
      console.log(e.type, e.action);
    },
    'cropmove.cropper': function (e) {
      console.log(e.type, e.action);
    },
    'cropend.cropper': function (e) {
      console.log(e.type, e.action);
    },
    'crop.cropper': function (e) {
      console.log(e.type, e.x, e.y, e.width, e.height, e.rotate, e.scaleX, e.scaleY);
    },
    'zoom.cropper': function (e) {
      console.log(e.type, e.ratio);
    }
  }).cropper(options);


  // Buttons
  if (!$.isFunction(document.createElement('canvas').getContext)) {
    $('button[data-method="getCroppedCanvas"]').prop('disabled', true);
  }

  if (typeof document.createElement('cropper').style.transition === 'undefined') {
    $('button[data-method="rotate"]').prop('disabled', true);
    $('button[data-method="scale"]').prop('disabled', true);
  }


  // Download
  if (typeof $download[0].download === 'undefined') {
    $download.addClass('disabled');
  }


  // Options
  $('.docs-toggles').on('change', 'input', function () {
    var $this = $(this);
    var name = $this.attr('name');
    var type = $this.prop('type');
    var cropBoxData;
    var canvasData;

    if (!$image.data('cropper')) {
      return;
    }

    if (type === 'checkbox') {
      options[name] = $this.prop('checked');
      cropBoxData = $image.cropper('getCropBoxData');
      canvasData = $image.cropper('getCanvasData');

      options.built = function () {
        $image.cropper('setCropBoxData', cropBoxData);
        $image.cropper('setCanvasData', canvasData);
      };
    } else if (type === 'radio') {
      options[name] = $this.val();
    }

    $image.cropper('destroy').cropper(options);
  });


  // Methods
  $('.docs-buttons').on('click', '[data-method]', function () {
    var $this = $(this);
    var data = $this.data();
    var $target;
    var result;

    if ($this.prop('disabled') || $this.hasClass('disabled')) {
      return;
    }

    if ($image.data('cropper') && data.method) {
      data = $.extend({}, data); // Clone a new one

      if (typeof data.target !== 'undefined') {
        $target = $(data.target);

        if (typeof data.option === 'undefined') {
          try {
            data.option = JSON.parse($target.val());
          } catch (e) {
            console.log(e.message);
          }
        }
      }

      result = $image.cropper(data.method, data.option, data.secondOption);

      switch (data.method) {
        case 'scaleX':
        case 'scaleY':
          $(this).data('option', -data.option);
          break;

        case 'getCroppedCanvas':
          if (result) {

            // Bootstrap's Modal
            $('#getCroppedCanvasModal').modal().find('.modal-body').html(result);

            if (!$download.hasClass('disabled')) {
              $download.attr('href', result.toDataURL('image/jpeg'));
            }
          }

          break;
      }

      if ($.isPlainObject(result) && $target) {
        try {
          $target.val(JSON.stringify(result));
        } catch (e) {
          console.log(e.message);
        }
      }

    }
  });


  // Keyboard
  $(document.body).on('keydown', function (e) {

    if (!$image.data('cropper') || this.scrollTop > 300) {
      return;
    }

    switch (e.which) {
      case 37:
        e.preventDefault();
        $image.cropper('move', -1, 0);
        break;

      case 38:
        e.preventDefault();
        $image.cropper('move', 0, -1);
        break;

      case 39:
        e.preventDefault();
        $image.cropper('move', 1, 0);
        break;

      case 40:
        e.preventDefault();
        $image.cropper('move', 0, 1);
        break;
    }

  });


  // Import image
  var $inputImage = $('#inputImage');
  var URL = window.URL || window.webkitURL;
  var blobURL;

  if (URL) {
    $inputImage.change(function () {
      var files = this.files;
      var file;

      if (!$image.data('cropper')) {
        return;
      }

      if (files && files.length) {
        file = files[0];

        if (/^image/w+$/.test(file.type)) {
          blobURL = URL.createObjectURL(file);
          $image.one('built.cropper', function () {

            // Revoke when load complete
            URL.revokeObjectURL(blobURL);
          }).cropper('reset').cropper('replace', blobURL);
          $inputImage.val('');
        } else {
          window.alert('Please choose an image file.');
        }
      }
    });
  } else {
    $inputImage.prop('disabled', true).parent().addClass('disabled');
  }

});

需要添加的css样式

 

style.css

 

.avatar-view {
    display: block;
    margin: 0 auto;
    height: 220px;
    width: 220px;
    border: 3px solid #fff;
    border-radius: 5px;
    box-shadow: 0 0 5px rgba(0,0,0,.15);
    cursor: pointer;
    overflow: hidden;
}

.avatar-view img {
    width: 100%;
}

.avatar-body {
    padding-right: 15px;
    padding-left: 15px;
}

.avatar-upload {
    overflow: hidden;
}

.avatar-upload label {
    display: block;
    float: left;
    clear: left;
    width: 100px;
}

.avatar-upload input {
    display: block;
    margin-left: 110px;
}

.avater-alert {
    margin-top: 10px;
    margin-bottom: 10px;
}

.avatar-wrapper {
    height: 364px;
    width: 100%;
    margin-top: 15px;
    box-shadow: inset 0 0 5px rgba(0,0,0,.25);
    background-color: #fcfcfc;
    overflow: hidden;
}

.avatar-wrapper img {
    display: block;
    height: auto;
    max-width: 100%;
}

.avatar-preview {
    float: left;
    margin-top: 15px;
    margin-right: 15px;
    border: 1px solid #eee;
    border-radius: 4px;
    background-color: #fff;
    overflow: hidden;
}

.avatar-preview:hover {
    border-color: #ccf;
    box-shadow: 0 0 5px rgba(0,0,0,.15);
}

.avatar-preview img {
    width: 100%;
}

.preview-lg {
    height: 200px;
    width: 200px;
    margin-top: 15px;
}

.preview-md {
    height: 100px;
    width: 100px;
}

.preview-sm {
    height: 50px;
    width: 50px;
}
.preview-xs{
    height:30px;
    width:30px;]
}

@media (min-width: 992px) {
    .avatar-preview {
        float: none;
    }
}

.avatar-btns {
    margin-top: 30px;
    margin-bottom: 15px;
}

.avatar-btns .btn-group {
    margin-right: 5px;
}

.loading {
    display: none;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: #fff url("patterns/loading.gif") no-repeat center center;
    opacity: .75;
    filter: alpha(opacity=75);
    z-index: 20140628;
}

现在前端的基本完成。现在最重要的来了,就是后台java 处理了。在网上找过很多,发现没有,关于springmvc的,上面的内容基本上在网上找到,下面的springmvc的,关于图像处理的,就是我个人做的。好像网上有直接在前端进行剪裁的,可惜我不会啊,所以我还是老老实实的在后台处理了。

 

 

package com.cx.wxs.action.image;

import java.io.File;
import java.sql.Timestamp;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cx.wxs.dto.BSiteDto;
import com.cx.wxs.dto.IAlbumDto;
import com.cx.wxs.dto.IImageDto;
import com.cx.wxs.dto.UUserDto;
import com.cx.wxs.service.BSiteService;
import com.cx.wxs.service.IImageService;
import com.cx.wxs.service.UUserService;
import com.cx.wxs.utils.DateUtils;
import com.cx.wxs.utils.clientInfo;
import com.cx.wxs.utils.imageUtils;

/**
 * @author roychenyi
 * @date   2016-3-29 下午9:22:01
 */
@Controller
@RequestMapping("/{vip}/image")
public class imageAction {

 @Resource
 private IImageService iImageService;
 @Resource
 private BSiteService bSiteService;
 @Resource
 private UUserService uUserService;

 /**
  * @return the bSiteService
  */
 public BSiteService getbSiteService() {
  return bSiteService;
 }

 /**
  * @param bSiteService the bSiteService to set
  */
 public void setbSiteService(BSiteService bSiteService) {
  this.bSiteService = bSiteService;
 }

 /**
  * @return the uUserService
  */
 public UUserService getuUserService() {
  return uUserService;
 }

 /**
  * @param uUserService the uUserService to set
  */
 public void setuUserService(UUserService uUserService) {
  this.uUserService = uUserService;
 }

 /**
  * @return the iImageService
  */
 public IImageService getiImageService() {
  return iImageService;
 }

 /**
  * @param iImageService the iImageService to set
  */
 public void setiImageService(IImageService iImageService) {
  this.iImageService = iImageService;
 }
 @RequestMapping(value="/updateuserlogo")
 @ResponseBody
 public IImageDto updateUserLogo( @PathVariable("vip") String vip,
    Integer x, Integer y, Integer width, Integer height,Integer degree,
   @RequestParam(value = "avatar_file") MultipartFile imageFile, HttpServletRequest request,HttpServletResponse response){
  IImageDto imageDto=new IImageDto();
  //获取服务器的实际路径
   String realPath = request.getSession().getServletContext().getRealPath("/");
     System.out.println("x:"+x+"y:"+y+"width:"+width+"height:"+height+"degree:"+degree);
  System.out.println(realPath);
  //需要上传的路径,我的路径根据用户的和当前日期划分路径
  String resourcePath="upload/image";
  UUserDto userDto=(UUserDto) request.getSession().getAttribute("user");
  resourcePath+="/"+userDto.getUserId();

   if(imageFile!=null){
    try{
   //文件名
    String name= imageFile.getOriginalFilename();
    //获取时间的路径
    Date date=new Date();    
    int year=DateUtils.getYear(date);
    int month=DateUtils.getMonth(date);
    int day=DateUtils.getDay(date);
    resourcePath+="/"+year+"/"+month+"/"+day+"/";
    File dir=new File(realPath+resourcePath);
    if(!dir.exists()){
     dir.mkdirs();
    }
    //先把用户上传到原图保存到服务器上
    File file=new File(dir,date.getTime()+".jpg");
    imageFile.transferTo(file);
    if(file.exists()){
     String src=realPath+resourcePath+date.getTime();

     boolean[] flag=new boolean[6];
     //旋转后剪裁图片
     flag[0]=imageUtils.cutAndRotateImage(src+".jpg", src+"_s.jpg", x, y, width, height, degree);
     //缩放图片,生成不同大小的图片,应用于不同的大小的头像显示
     flag[1]= imageUtils.scale2(src+"_s.jpg", src+"_s_200.jpg", 200, 200, true);
     flag[2]= imageUtils.scale2(src+"_s.jpg", src+"_s_100.jpg", 100, 100, true);
     flag[3]= imageUtils.scale2(src+"_s.jpg", src+"_s_50.jpg", 50, 50, true);
     flag[4]= imageUtils.scale2(src+"_s.jpg", src+"_s_30.jpg", 30, 30, true);
     flag[5]= imageUtils.scale2(file.getPath(), src+"_200.jpg", 200, 200, true);

     if(flag[0]&&flag[1]&&flag[2]&&flag[3]&&flag[4]&&flag[5]){
      //图像处理完成,将数据写入数据库中
      imageDto.setYear((short) year);
      imageDto.setMount((short)month);
      imageDto.setDay((short)day);
      imageDto.setUUserDto(userDto);
      imageDto.setName(date.getTime()+".jpg");
      imageDto.setFileName(name);
      imageDto.setUrl(resourcePath+"/"+date.getTime()+".jpg");
      imageDto.setPreviewUrl(resourcePath+"/"+date.getTime()+"_200.jpg");
      imageDto.setTime(new Timestamp(date.getTime()));
      imageDto.setWidth((short)imageUtils.getImageWidth(file.getPath()));
      imageDto.setHeight((short)imageUtils.getImageHeight(file.getPath()));
      imageDto.setClientIp(clientInfo.getIpAddr(request));
      imageDto.setClientAgent(clientInfo.getAgent(request));
      imageDto.setClientType((short)(clientInfo.isMoblie(request)?1:0));
      imageDto.setStatus((short)1);
      imageDto.setExt3(resourcePath+"/"+date.getTime()+"_s_200.jpg");
      imageDto.setExt4(resourcePath+"/"+date.getTime()+"_s_100.jpg");
     //设置相册,头像设置进入默认相册
      IAlbumDto albumDto=new IAlbumDto();
      albumDto.setAlbumId(1);
      imageDto.setIAlbumDto(albumDto);
      int id= iImageService.addIImage(imageDto);
      if(id>0){
       BSiteDto siteDto=userDto.getBSiteDto();
       siteDto.setLogo(resourcePath+"/"+date.getTime()+"_s_100.jpg");
       siteDto.setLastTime( new Timestamp(date.getTime()));
       bSiteService.updateBSite(siteDto);
       userDto.setPortrait(resourcePath+"/"+date.getTime()+"_s_30.jpg");
       uUserService.updateUuser(userDto);
       userDto=uUserService.getUuser(userDto);
       imageDto.setLoginFlag("1");
       return imageDto;
      }
     }
    }
    }catch (Exception e) {
    // TODO: handle exception
     e.printStackTrace();
     return imageDto;
   }

   }
  return imageDto;
 }
}

 

下面是图像处理的工具类。imageUtils.java.欢迎借鉴引用。(我也是在我网上找了很多进行参考的)

 

package com.cx.wxs.utils;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.cx.wxs.dto.IImageDto;


/**
 * @author roychenyi
 * @date   2016-3-30 上午10:11:39
 */
public class imageUtils {
 private static Log log = LogFactory.getLog(imageUtils.class);


 /***
  * 获取图片的类型
  * @param o
  * @return
  * @date   2016-3-30下午4:59:36
  */
 private static String getFormatName(Object o) {
        try {
            ImageInputStream iis = ImageIO.createImageInputStream(o);
            Iterator iter = ImageIO.getImageReaders(iis);
            if (!iter.hasNext()) {
                return null;
            }

            ImageReader reader = iter.next();
            iis.close();
            return reader.getFormatName();
        } catch (IOException e) {
        }
        return null;
    }

 /**
     * 使用ImageReader获取图片尺寸
     * 
     * @param src
     *            源图片路径
     */
    public void getImageSizeByImageReader(String src) {
        long beginTime = new Date().getTime();
        File file = new File(src);
        try {
            Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
            ImageReader reader = (ImageReader) readers.next();
            ImageInputStream iis = ImageIO.createImageInputStream(file);
            reader.setInput(iis, true);
            System.out.println("width:" + reader.getWidth(0));
            System.out.println("height:" + reader.getHeight(0));
        } catch (IOException e) {
            e.printStackTrace();
        }
        long endTime = new Date().getTime();
        System.out.println("使用[ImageReader]获取图片尺寸耗时:[" + (endTime - beginTime)+"]ms");
    }

    /**
     * 使用BufferedImage获取图片尺寸
     * 
     * @param src
     *            源图片路径
     */
    public void getImageSizeByBufferedImage(String src) {
        long beginTime = new Date().getTime();
        File file = new File(src);
        FileInputStream is = null;
        try {
            is = new FileInputStream(file);
        } catch (FileNotFoundException e2) {
            e2.printStackTrace();
        }
        BufferedImage sourceImg = null;
        try {
            sourceImg = javax.imageio.ImageIO.read(is);
            System.out.println("width:" + sourceImg.getWidth());
            System.out.println("height:" + sourceImg.getHeight());
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        long endTime = new Date().getTime();
        System.out.println("使用[BufferedImage]获取图片尺寸耗时:[" + (endTime - beginTime)+"]ms");
    }

    /***
     * 获取图片的宽
     * @param srcImageFile
     * @return
     * @date   2016-3-30下午9:01:08
     */
    public static int  getImageWidth(String srcImageFile){
         try {
          File file = new File(srcImageFile);
             Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
             ImageReader reader = (ImageReader) readers.next();
             ImageInputStream iis = ImageIO.createImageInputStream(file);
             reader.setInput(iis, true);

             return reader.getWidth(0);
         } catch (IOException e) {
             e.printStackTrace();
             return 0;
         }
    }
    /***
     * 获取文件的高
     * @param srcImageFile
     * @return
     * @date   2016-3-30下午9:02:19
     */
    public static int getImageHeight(String srcImageFile){
     File file = new File(srcImageFile);
        try {
            Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
            ImageReader reader = (ImageReader) readers.next();
            ImageInputStream iis = ImageIO.createImageInputStream(file);
            reader.setInput(iis, true);

            return reader.getHeight(0);
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }
    }

 /***
  * 剪裁图片
  * @param src
  * @param dest
  * @param x  起点横坐标
  * @param y  纵坐标
  * @param w  长
  * @param h  高
  * @throws IOException
  * @date   2016-3-30下午12:19:10
  */
  public static boolean cutImage(String src,String dest,int x,int y,int w,int h) {   
         try{
   Iterator iterator = ImageIO.getImageReadersByFormatName("jpg");   
         ImageReader reader = (ImageReader)iterator.next();   
         InputStream in=new FileInputStream(src);  
         ImageInputStream iis = ImageIO.createImageInputStream(in);   
         reader.setInput(iis, true);   
         ImageReadParam param = reader.getDefaultReadParam(); 
         x=(x>0?x:0);
         y=(y>0?y:0);
         Rectangle rect = new Rectangle(x, y, w,h);    
         param.setSourceRegion(rect);   
         BufferedImage bi = reader.read(0,param);     
         ImageIO.write(bi, "jpg", new File(dest));    
         return true;
         }catch (Exception e) {
   // TODO: handle exception
          e.printStackTrace();
          return false;
  }

  } 
  /***
   * 图片旋转指定角度
   * @param bufferedimage 图像
   * @param degree      角度
   * @return
   * @date   2016-3-30下午3:10:27
   */
  public static BufferedImage rotateImage(final BufferedImage bufferedimage,
             final int degree) {
         int w = bufferedimage.getWidth();
         int h = bufferedimage.getHeight();
         int type = bufferedimage.getColorModel().getTransparency();
         BufferedImage img;
         Graphics2D graphics2d;
         (graphics2d = (img = new BufferedImage(w, h, type))
                 .createGraphics()).setRenderingHint(
                 RenderingHints.KEY_INTERPOLATION,
                 RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    //     graphics2d.setBackground(Color.white);
         graphics2d.setPaint(Color.WHITE);
         graphics2d.fillRect(0, 0, w, h);
         graphics2d.rotate(Math.toRadians(degree), w / 2, h / 2);
         graphics2d.drawImage(bufferedimage, 0, 0,Color.WHITE, null);
         graphics2d.dispose();
         return img;
     }
  public static boolean rotateImage(String srcImageFile, String result,
    int degree){
   try{
    BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件
    BufferedImage tag= rotateImage(src, degree);

    ImageIO.write(tag, "JPEG", new File(result));

    return true;
   }catch (Exception e) {
    // TODO: handle exception
    return false;
   }
  }

  public static BufferedImage Rotate(Image src, int angel) {  
         int src_width = src.getWidth(null);  
         int src_height = src.getHeight(null); 
       //  angel=angel>0?angel:(360-angel);
         // calculate the new image size  
         Rectangle rect_des = CalcRotatedSize(new Rectangle(new Dimension(  
                 src_width, src_height)), angel);  

         BufferedImage res = null;  
         res = new BufferedImage(rect_des.width, rect_des.height,  
                 BufferedImage.TYPE_INT_RGB);  
         Graphics2D g2 = res.createGraphics();  
         g2.setPaint(Color.WHITE);
         g2.fillRect(0, 0, rect_des.width,  rect_des.height);
         // transform  
         g2.translate((rect_des.width - src_width) / 2,  
                 (rect_des.height - src_height) / 2);  
         g2.rotate(Math.toRadians(angel), src_width / 2, src_height / 2);  

         g2.drawImage(src, null, null);  
         return res;  
     }  

     public static Rectangle CalcRotatedSize(Rectangle src, int angel) {  
         // if angel is greater than 90 degree, we need to do some conversion  
         if (angel >= 90) {  
             if(angel / 90 % 2 == 1){  
                 int temp = src.height;  
                 src.height = src.width;  
                 src.width = temp;  
             }  
             angel = angel % 90;  
         }  

         double r = Math.sqrt(src.height * src.height + src.width * src.width) / 2;  
         double len = 2 * Math.sin(Math.toRadians(angel) / 2) * r;  
         double angel_alpha = (Math.PI - Math.toRadians(angel)) / 2;  
         double angel_dalta_width = Math.atan((double) src.height / src.width);  
         double angel_dalta_height = Math.atan((double) src.width / src.height);  

         int len_dalta_width = (int) (len * Math.cos(Math.PI - angel_alpha  
                 - angel_dalta_width));  
         int len_dalta_height = (int) (len * Math.cos(Math.PI - angel_alpha  
                 - angel_dalta_height));  
         int des_width = src.width + len_dalta_width * 2;  
         int des_height = src.height + len_dalta_height * 2;  
         return new java.awt.Rectangle(new Dimension(des_width, des_height));  
     }

     public static boolean Rotate(String srcImageFile, String result,
             int degree){
      try{
       degree=degree>0?degree:(360-degree);
       BufferedImage src = ImageIO.read(new File(srcImageFile));  
             BufferedImage tag = Rotate(src, degree);
             ImageIO.write(tag, "JPEG", new File(result));     
     return true;
      }catch (Exception e) {
    // TODO: handle exception
       e.printStackTrace();
       return false;
   }
     }


 public static boolean cutAndRotateImage(String srcImageFile,String dest,int x,int y,int w,int h,int degree){
  try{
   BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件
   BufferedImage tag= Rotate(src, degree);
    Iterator iterator = ImageIO.getImageReadersByFormatName("jpg");   
          ImageReader reader = (ImageReader)iterator.next();   
     //     InputStream in=new FileInputStream(tag); 
          ByteArrayOutputStream bs = new ByteArrayOutputStream();  
          ImageOutputStream ios = ImageIO.createImageOutputStream(bs);  
          ImageIO.write(tag, "jpg", ios);
          InputStream in=new  ByteArrayInputStream(bs.toByteArray());
          ImageInputStream iis=ImageIO.createImageInputStream(in);
          reader.setInput(iis, true);   
          ImageReadParam param = reader.getDefaultReadParam(); 
          x=(x>0?x:0);
          y=(y>0?y:0);
          Rectangle rect = new Rectangle(x, y, w,h);    
          param.setSourceRegion(rect);   
          BufferedImage bi = reader.read(0,param);     
          ImageIO.write(bi, "jpg", new File(dest));  
   return true;
  }catch (Exception e) {
   // TODO: handle exception
   return false;
  }
 }

  /***
   * 按照比例缩放
   * @param srcImageFile
   * @param result  
   * @param scale 缩放比例
   * @param flag 缩放选择:true 放大; false 缩小;
   * @return
   * @date   2016-3-30下午2:39:44
   */
  public  static boolean scale(String srcImageFile, String result,
             int scale, boolean flag) {
         try {
          File file = new File(srcImageFile);
             BufferedImage src = ImageIO.read(file); // 读入文件
              Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
              ImageReader reader = (ImageReader) readers.next();
              ImageInputStream iis = ImageIO.createImageInputStream(file);
              reader.setInput(iis, true);
             int width = reader.getWidth(0); // 得到源图宽
             int height = reader.getHeight(0); // 得到源图长
             if (flag) {// 放大
                 width = width * scale;
                 height = height * scale;
             } else {// 缩小
                 width = width / scale;
                 height = height / scale;
             }
             Image image = src.getScaledInstance(width, height,
                     Image.SCALE_DEFAULT);
             BufferedImage tag = new BufferedImage(width, height,
                     BufferedImage.TYPE_INT_RGB);
             Graphics g = tag.getGraphics();
             g.drawImage(image, 0, 0, null); // 绘制缩小后的图
             g.dispose();
             ImageIO.write(tag, "jpg", new File(result));// 输出到文件流
             return true;
         } catch (IOException e) {
             e.printStackTrace();
             return false;
         }
     }
  /***
   * 缩放图像,按照长宽缩放
   * @param srcImageFile
   * @param result
   * @param height  变换后的高度
   * @param width   变换后的长度
   * @param bb      比例不对称时,是否补白,true 补白;false 不补白
   * @return

   * @date   2016-3-30下午2:44:37
   */
  public  static boolean scale2(String srcImageFile, String result, int height, int width, boolean bb) {
         try {
             double ratio = 0.0; // 缩放比例
             File file = new File(srcImageFile);
             BufferedImage bi = ImageIO.read(file); // 读入文件
              Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
              ImageReader reader = (ImageReader) readers.next();
              ImageInputStream iis = ImageIO.createImageInputStream(file);
              reader.setInput(iis, true);
             int width1 = reader.getWidth(0); // 得到源图宽
             int height1 = reader.getHeight(0); // 得到源图长
             Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);
             // 计算比例
             if ((height1 > height) || (width1 > width)) {
                 if (height1 > width1) {
                     ratio = (new Integer(height)).doubleValue()
                             / height1;
                 } else {
                     ratio = (new Integer(width)).doubleValue() / width1;
                 }
                 AffineTransformOp op = new AffineTransformOp(AffineTransform
                         .getScaleInstance(ratio, ratio), null);
                 itemp = op.filter(bi, null);
             }
             if (bb) {//补白
                 BufferedImage image = new BufferedImage(width, height,
                         BufferedImage.TYPE_INT_RGB);
                 Graphics2D g = image.createGraphics();
                 g.setColor(Color.white);
                 g.fillRect(0, 0, width, height);
                 if (width == itemp.getWidth(null))
                     g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2,
                             itemp.getWidth(null), itemp.getHeight(null),
                             Color.white, null);
                 else
                     g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0,
                             itemp.getWidth(null), itemp.getHeight(null),
                             Color.white, null);
                 g.dispose();
                 itemp = image;
             }
             ImageIO.write((BufferedImage) itemp, "JPEG", new File(result));
             return true;
         } catch (IOException e) {
             e.printStackTrace();
             return false;
         }
     }
  /***
   * 转换图像格式
   * @param srcImageFile 原图像地址
   * @param formatName   转换类型
   * @param destImageFile 转换后的地址
   * @return
   * @author roychenyi
   * @date   2016-3-30下午2:49:15
   */
     public  static boolean convert(String srcImageFile, String formatName, String destImageFile) {
         try {
             File f = new File(srcImageFile);
             f.canRead();
             f.canWrite();
             BufferedImage src = ImageIO.read(f);
             ImageIO.write(src, formatName, new File(destImageFile));
             return true;
         } catch (Exception e) {
             e.printStackTrace();
             return false;
         }
     }

     /**
      * 彩色转为黑白 
      * @param srcImageFile 源图像地址
      * @param destImageFile 目标图像地址
      */
     public final static void gray(String srcImageFile, String destImageFile) {
         try {
             BufferedImage src = ImageIO.read(new File(srcImageFile));
             ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
             ColorConvertOp op = new ColorConvertOp(cs, null);
             src = op.filter(src, null);
             ImageIO.write(src, "jpg", new File(destImageFile));
         } catch (IOException e) {
             e.printStackTrace();
         }
     }

     /**
      * 给图片添加图片水印
      * @param pressImg 水印图片
      * @param srcImageFile 源图像地址
      * @param destImageFile 目标图像地址
      * @param x 修正值。 默认在中间
      * @param y 修正值。 默认在中间
      * @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字
      */
     public  static boolean pressImage(String pressImg, String srcImageFile,String destImageFile,
             int x, int y, float alpha) {
         try {
          File file = new File(srcImageFile);
             BufferedImage src = ImageIO.read(file); // 读入文件
              Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
              ImageReader reader = (ImageReader) readers.next();
              ImageInputStream iis = ImageIO.createImageInputStream(file);
              reader.setInput(iis, true);
             int width = reader.getWidth(0); // 得到源图宽
             int height = reader.getHeight(0); // 得到源图长
             BufferedImage image = new BufferedImage(width, height,
                     BufferedImage.TYPE_INT_RGB);
             Graphics2D g = image.createGraphics();
             g.drawImage(src, 0, 0, width, height, null);
             // 水印文件
             Image src_biao = ImageIO.read(new File(pressImg));
             int wideth_biao = src_biao.getWidth(null);
             int height_biao = src_biao.getHeight(null);
             g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                     alpha));
             g.drawImage(src_biao, (width-wideth_biao-x) ,
                     (height-height_biao-y) , wideth_biao, height_biao, null);
             // 水印文件结束
             g.dispose();
             ImageIO.write((BufferedImage) image,  "jpg", new File(destImageFile));
             return true;
         } catch (Exception e) {
             e.printStackTrace();
             return false;
         }
     }

     /**
      * 给图片添加文字水印
      * @param pressText 水印文字
      * @param srcImageFile 源图像地址
      * @param destImageFile 目标图像地址
      * @param fontName 水印的字体名称
      * @param fontStyle 水印的字体样式
      * @param color 水印的字体颜色
      * @param fontSize 水印的字体大小
      * @param x 修正值
      * @param y 修正值
      * @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字
      */
     public  static boolean pressText(String pressText,
             String srcImageFile, String destImageFile, String fontName,
             int fontStyle, Color color, int fontSize,int x,
             int y, float alpha) {
         try {
          File file = new File(srcImageFile);
             BufferedImage src = ImageIO.read(file); // 读入文件
              Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
              ImageReader reader = (ImageReader) readers.next();
              ImageInputStream iis = ImageIO.createImageInputStream(file);
              reader.setInput(iis, true);
             int width = reader.getWidth(0); // 得到源图宽
             int height = reader.getHeight(0); // 得到源图长
             BufferedImage image = new BufferedImage(width, height,
                     BufferedImage.TYPE_INT_RGB);
             Graphics2D g = image.createGraphics();
             g.drawImage(src, 0, 0, width, height, null);
             g.setColor(color);
             g.setFont(new Font(fontName, fontStyle, fontSize));
             g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                     alpha));
             // 在指定坐标绘制水印文字
             g.drawString(pressText, (width - (getLength(pressText) * fontSize))
                     / 2 + x, (height - fontSize) / 2 + y);
             g.dispose();
             ImageIO.write(image, "jpg", new File(destImageFile));// 输出到文件流
             return true;
         } catch (Exception e) {
             e.printStackTrace();
             return false;
         }
     }

     /**
      * 计算text的长度(一个中文算两个字符)
      * @param text
      * @return
      */
     public  static int getLength(String text) {
         int length = 0;
         for (int i = 0; i < text.length(); i++) {
             if (new String(text.charAt(i) + "").getBytes().length > 1) {
                 length += 2;
             } else {
                 length += 1;
             }
         }
         return length / 2;
     }


     public static void main(String[] args) {
  String src="D:/0.jpg";
  /*  imageUtils.cutImage(src, "D://1cut.jpg", -10, 40, 100000, 560);
  imageUtils.rotateImage(src, "D:/2rotate.jpg", -30);
  imageUtils.rotateImage(src, "D:/2rotate1.png", 30);
  imageUtils.Rotate(src, "D://2rotate2.jpg", 330);
  imageUtils.Rotate(src,"D://2rotate21.jpg",30);
  imageUtils.cutAndRotateImage(src, "D://9cutRotate1.jpg", 244, 427, 614, 614, 0);
  imageUtils.scale(src, "D://3scale1.jpg", 3, false);
  imageUtils.scale2(src, "D://4scale2.jpg", 780,560, false);
  imageUtils.convert(src, "png", "D://5convert.png");
  imageUtils.gray(src,"D://6gray.jpg");
  imageUtils.pressImage("D://3scale1.jpg", src, "D://7pressImage.jpg", 100, 100, 0.9f);
  imageUtils.pressText("图片1414", src, "D://8pressText.jpg", "宋体", Font.BOLD, Color.black, 80, 10, 10,0.6f);
*/
   imageUtils util = new imageUtils();
         util.getImageSizeByImageReader(src);
         util.getImageSizeByBufferedImage(src);
         System.out.println(getImageHeight(src));
         imageUtils.Rotate("E:\apache-tomcat-7.0.59\webapps\wxs\upload\image\1\2016\3\30\1459347622160.jpg","E:\apache-tomcat-7.0.59\webapps\wxs\upload/image/1/2016/3/30/1459347622160_s.jpg", 90);
         imageUtils.Rotate("E:/apache-tomcat-7.0.59/webapps/wxs/upload/image/1/2016/3/30/1459349306443_s.jpg", "E:/apache-tomcat-7.0.59/webapps/wxs/upload/image/1/2016/3/30/1459349306443_s_200.jpg", 45);
 }
}

web 网站头像上传处理 (springmvc +bootstrap+cropper) 制作头像上传。请根据您的实际需求,修改代码,不完全正确,仅供参考! 前端页面设计...

本文实例为大家分享了JavaScript头像上传插件源码,供大家参考,具体内容如下

我们要完成头像上传功能,一共要写两个php页面,第一个页面我们叫做touxiang.php,第二个页面我们叫做upload.php

效果图:

1.touxiang.php

图片 3

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <title>无标题文档</title>
 6 
 7 <link href="bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
 8 <script src="bootstrap-3.3.7-dist/js/jquery-1.11.2.min.js"></script>
 9 <script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
10 
11 <style type="text/css">
12 #yl{ width:200px; height:200px; background-image:url(img/avatar.png); background-size:200px 200px;}
13 #file{ width:200px; height:200px; float:left; opacity:0;}
14 .modal-content{ width:500px;}
15 .kk{ margin-left:130px;}
16 </style>
17 
18 </head>
19 
20 <body>
21 
22 
23 
24 <!-- 按钮触发模态框 -->
25 <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
26     上传头像
27 </button>
28 <!-- 模态框(Modal) -->
29 <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
30     <div class="modal-dialog">
31         <div class="modal-content">
32             <div class="modal-header">
33                 <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
34                     &times;
35                 </button>
36                 <h4 class="modal-title" id="myModalLabel">
37                     上传头像
38                 </h4>
39             </div>
40             <div class="modal-body">
41                 <form id="sc" action="upload.php" method="post" enctype="multipart/form-data" target="shangchuan">
42     
43     <input type="hidden" name="tp" value="" id="tp" />
44     
45     <div id="yl" class="kk">
46         <input type="file" name="file" id="file" onchange="document.getElementById('sc').submit()" />
47     </div>
48     
49     
50     
51 </form>
52 
53 <iframe style="display:none" name="shangchuan" id="shangchuan">
54 </iframe>
55 
56             </div>
57             <div class="modal-footer">
58                 <button type="button" class="btn btn-default" data-dismiss="modal">关闭
59                 </button>
60                 <!--<button type="button" class="btn btn-primary">
61                     提交更改
62                 </button>-->
63                 
64             </div>
65         </div><!-- /.modal-content -->
66     </div><!-- /.modal -->
67 </div>
68 
69 
70 </body>
71 
72 <script type="text/javascript">
73 
74 //回调函数,调用该方法传一个文件路径,该变背景图
75 function showimg(url)
76 {
77     var div = document.getElementById("yl");
78     div.style.backgroundImage = "url("+url+")";
79     
80     document.getElementById("tp").value = url;
81 }
82 
83 </script>
84 
85 </html>

图片 4

在这个页面我们需要引入一个模态框和bootstrap.min.css,jquery-1.11.2.min.js,bootstrap.min.js三个文件

图片 5

2.upload.php

图片 6

 1 <?php
 2 
 3 if($_FILES["file"]["error"])
 4 {
 5     echo $_FILES["file"]["error"];
 6 }
 7 else
 8 {
 9     if(($_FILES["file"]["type"]=="image/jpeg" || $_FILES["file"]["type"]=="image/png")&& $_FILES["file"]["size"]<1024000000)
10     {
11         $fname = "./img/".date("YmdHis").$_FILES["file"]["name"];    
12         
13         $filename = iconv("UTF-8","gb2312",$fname);
14         
15         if(file_exists($filename))
16         {
17             echo "<script>alert('该文件已存在!');</script>";
18         }
19         else
20         {
21             move_uploaded_file($_FILES["file"]["tmp_name"],$filename);
22             
23             unlink($_POST["tp"]);
24             
25             echo "<script>parent.showimg('{$fname}');</script>";
26         }
27         
28     }
29 }

源码:
cxc.js      

网页显示效果如下:

/* cxc.js 频繁操作公共接口 */ 
var $ = function (id) { 
 return document.getElementById(id); 
}; //通过id获取dom对象 
var A = function (msg) { 
 alert(msg); 
}; //alert的简写 
var EmptyFun = function () { 
}; // 空方法 
var setL = function (dom, L) { 
 dom.style.left = L + "px"; 
}; // 设置 dom 的 left 
var setT = function (dom, T) { 
 dom.style.top = T + "px"; 
}; // 设置 dom 的 top 
var setLT = function (dom, L, T) { 
 dom.style.left = L + "px"; 
 dom.style.top = T + "px"; 
}; //同时设置 dom 的 left top 
var getLT = function (dom) { 
 return [parseInt(dom.style.left), parseInt(dom.style.top)]; 
}; // 返回dom的left和top值,类型为整型数组[int,int] 
var setW = function (W) { 
 dom.style.width = W + "px"; 
};  // 设置 dom 的 width 
var setH = function (H) { 
 dom.style.height = H + "px"; 
};  // 设置 dom 的 height 
var setWH = function (dom, W, H) { 
 dom.style.width = W + "px"; 
 dom.style.height = H + "px"; 
};  //同时设置 dom 的 width height 
var getWH = function (dom) { 
 return [parseInt(dom.style.width), parseInt(dom.style.height)]; 
}; // 返回dom的 width 和 height 值,类型为整型数组[int,int] 
var setLTWH = function (dom, L, T, W, H) { 
 dom.style.left = L + "px"; 
 dom.style.top = T + "px"; 
 dom.style.width = W + "px"; 
 dom.style.height = H + "px"; 
}; //同时设置 dom 的 left top width height 
var getLTWH = function (dom) { 
 return [parseInt(dom.style.left), parseInt(dom.style.top), parseInt(dom.style.width), parseInt(dom.style.height)] 
};  // 返回dom的 left top width height 值,类型为整型数组[int,int,int,int] 
var setcursor = function (dom,shape) { 
 dom.style.cursor = shape; 
}; //设置鼠标经过dom的指针形状 
var EventsType = ["click", "mousedown", "mouseup", "mouseover", "mouseleave", "mousemove"];//事件类型 
var AddEvent = function (dom, type, fun) { 
 dom.addEventListener(type, fun, false); 
};  //添加dom对象的事件监听方法 
var AddEvent2 = function (dom, type1, fun1, type2, fun2) { 
 dom.addEventListener(type1, fun1, false); 
 dom.addEventListener(type2, fun2, false); 
};  //一次添加dom的两个事件监听方法 
var AddEvent3 = function (dom, type1, fun1, type2, fun2, type3, fun3) { 
 dom.addEventListener(type1, fun1, false); 
 dom.addEventListener(type2, fun2, false); 
 dom.addEventListener(type3, fun3, false); 
}; //一次添加dom的三个事件监听方法 
var DelEvent = function (dom, type, fun) { 
 dom.removeEventListener(type, fun, false); 
}; // 删除dom对象的事件监听方法 
var DelEvent2 = function (dom, type1, fun1, type2, fun2) { 
 dom.removeEventListener(type1, fun1, false); 
 dom.removeEventListener(type2, fun2, false); 
}; //一次删除dom对象的两个事件监听方法 
var DelEvent3 = function (dom, type1, fun1, type2, fun2, type3, fun3) { 
 dom.removeEventListener(type1, fun1, false); 
 dom.removeEventListener(type2, fun2, false); 
 dom.removeEventListener(type3, fun3, false); 
}; //一次删除dom对象的三个事件监听方法 
var inArray = function (str, arr) { 
 for (var i = 0; i < arr.length; i++) { 
  if (str == arr[i]) { 
   return true; 
  } 
 } 
 return false; 
}; // 判断字符串str是否存在于数组arr 
var cannotselect = function () { 
 window.getSelection().removeAllRanges(); 
}; //页面元素(文字、图片等)不能被选中 
var setStyle = function (dom, styleName, styleValue) { 
 dom.setAttribute("style", styleName + ":" + styleValue + ";"); 
}; //设置dom的 一个style 属性值 
var setStyle2 = function (dom, styleName1, styleValue1, styleName2, styleValue2) { 
 dom.setAttribute("style", styleName1 + ":" + styleValue1 + ";" + styleName2 + ":" + styleValue2 + ";"); 
};//一次设置dom的 两个style 属性值 
var delStyle = function (dom, styleName) { 
 dom.removeAttribute("style", styleName); 
};//删除dom的 一个style 属性值 
var delStyle2 = function (dom, styleName1, styleName2) { 
 dom.removeAttribute("style", styleName1); 
 dom.removeAttribute("style", styleName2); 
};//一次删除dom的 两个style 属性值 
var setAttr = function (dom, attrName, attrValue) { 
 dom.setAttribute(attrName, attrValue); 
};// 设置dom的 一个属性值 
var setAttr2 = function (dom, attrName1, attrValue1, attrName2, attrValue2) { 
 dom.setAttribute(attrName1, attrValue1); 
 dom.setAttribute(attrName2, attrValue2); 
};//一次设置dom的 两个属性值 
var delAttr = function (dom, attrName) { 
 dom.removeAttribute(attrName); 
};//删除dom的 一个属性值 
var delAttr2 = function (dom, attrName1, attrName2) { 
 dom.removeAttribute(attrName1); 
 dom.removeAttribute(attrName2); 
};//删除dom 的两个属性值 
var Click = function (dom) { 
 dom.click(); 
};// 点击dom 
var Hide = function (dom) { 
 dom.style.display = "none"; 
};// 隐藏dom 
var Show = function (dom) { 
 dom.style.display = "inline"; 
}; // 显示dom 
/* cxc.js 频繁操作公共接口 */ 

/* AJAX 接口 */ 
var url, method, msg; 
var xmlReq = new XMLHttpRequest(); 
var AJAX = function (url, method, msg, callback) { 
 xmlReq.open(method, url, true); 
 xmlReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
 xmlReq.onreadystatechange = function () { 
  if (xmlReq.readyState == 4) { 
   if (xmlReq.status == 200) { 
    callback(); 
   } 
   else { 
    A("bad status is " + xmlReq.status); 
   } 
  } 
 }; 
 xmlReq.send(msg); 
}; 
/* AJAX 接口 */ 

图片 7图片 8图片 9

one.js

好了,这样一个简单的头像上传就做好了,赶快试试吧!

/* one.js */ 
/* my website philosophy */ 
/* 
 注:一般网站,浏览器最大化时,没有横向滚动条,有纵向滚动条,页面缩放按比例只在合适的地方用到 
 <html>标签 不必加css和js控制 <body>标签 作为总父标签 用它控制整个页面的宽度和高度 
 <body>的宽度 一般为100%(考虑滚动条存在与否) 而高度可根据页面需求自定义 
 也就是说body的宽高就是页面的宽高 页面高度如果超出 浏览器窗口高度 出现滚动条 
*/ 
var one = { 
 screenW: null, //可用浏览器窗口的宽度 
 screenH: null, //可用浏览器窗口的高度 
 body: null,  //document.body对象 
 bodyW: null,  //body的宽度 
 bodyH: null,  //body的高度 
 avatar: null, //默认头像div 
 avatar_img:null, 
 main: null,  //处理上传图片的主要父div 
 mainW: 430,  //main的宽度 
 mainH:400,  //main的高度 
 mainL: null,  //main 的left位置 
 mainT:null,  //main 的top位置 
 top: null, 
 upfile:null, 
 center:null, 
 bigimg: null, 
 movebox: null, 
 moveimg: null, 
 d11: null, 
 d22: null, 
 d33: null, 
 TopLeft: null, 
 TopRight: null, 
 BottomRight: null, 
 BottomLeft: null, 
 p2: null, 
 p3:null 
}; 
var Init = function () { 
 ////////////////////////////////////////////////////////////////// 
 one.screenW = window.innerWidth; 
 one.screenH = window.innerHeight; 
 one.body = document.body; 
 one.bodyW = one.body.offsetWidth; 
 one.bodyH = one.screenH; //定义body的高度等于可用浏览器窗口的高度 
 one.body.setAttribute("style", "height:" + one.bodyH + "px;"); 
 ////////////////////////////////////////////////////////////////// 
 one.avatar = $("avatar"); 
 one.avatar_img = $("avatar_img"); 
 one.main = $("main"); 
 one.mainL = (one.bodyW - one.mainW) / 2; 
 one.mainT = (one.screenH - one.mainH) / 2; 
 /////////////////////////////////////////////////////////// 
 one.top = $("top"); 
 one.center = $("center"); 
 one.bigimg = $("bigimg"); 
 one.movebox = $("movebox"); 
 one.moveimg = $("moveimg"); 
 one.d11 = $("d11"); 
 one.d22 = $("d22"); 
 one.d33 = $("d33"); 
 /////////////////////////////////////////////////////////// 
 one.TopLeft = $("TopLeft"); 
 one.TopRight = $("TopRight"); 
 one.BottomRight = $("BottomRight"); 
 one.BottomLeft = $("BottomLeft"); 
 /////////////////////////////////////////////////////////// 
 one.p2 = $("p2"); 
 one.p3 = $("p3"); 
 /////////////////////////////////////////////////////////// 
 setLT(one.main, one.mainL, one.mainT); 
 Hide(one.main); 
}; 
var End = function () { 

}; 
window.onload = function () { 
 Init(); //初始化,获取页面上所有需要处理的标签对象,并赋初始值 
 Events(); //定义页面中的所有事件 
 End(); //js文件加载完成之后的处理工作 
};//dom元素全部加载完成,执行此方法 

Events.js

var downX, downY, oldL, oldT, tempWH, tempL, tempT, dxMax,tempMaxL,tempMaxT; 
var file, imgtype, imgsize, imgW, imgH, imgP, imgURL; 
var bigimgL, bigimgT; 
var moveboxWH, moveboxL, moveboxT, moveboxMinL, moveboxMinT, moveboxMaxL, moveboxMaxT; 
var moveimgL, moveimgT; 
var topL, topT; 
var gen = { 
 _moveboxWH:null, 
 _moveboxL: null, 
 _moveboxT: null, 
}; 
/* one.avatar Events start */ 
var avatar_click = function () { 
 one.upfile = document.createElement("input"); 
 setAttr2(one.upfile, "type", "file", "id", "upfile"); 
 this.parentNode.appendChild(one.upfile); 
 Click(one.upfile); 
 one.upfile.onchange = function () { 
  file = this.files[0]; 
  imgtype = file.type; 
  if (!fun.check_imgtype()) { 
   return; 
  } //检查文件类型 
  imgsize = file.size; 
  if (!fun.check_imgsize()) { 
   return; 
  }; //检查图片大小 
  var reader = new FileReader(); 
  reader.onload = function () { 
   fun.setImgWH(this.result, imgtype); 
   delete (reader); 
  }; 
  reader.readAsDataURL(file); 
  /////////////////////////// 
  this.parentNode.removeChild(one.upfile); 
 }; 
}; 
var avatar_mouseover = function () { 
 setStyle2(one.avatar, "border", "2px solid #46AFDC", "box-shadow", "0 0 5px #46AFDC"); 
}; 
var avatar_mouseleave = function () { 
 delStyle2(one.avatar, "border", "box-shadow"); 
}; 
/* one.avatar Events end */ 

/* one.top Events start */ 
var topLimit = function () { 
 if (topL < 0) 
  topL = 1; 
 else if (topL > one.bodyW - 432) 
  topL = one.bodyW - 432 - 1; 
 if (topT < 0) 
  topT = 1; 
 else if (topT > one.screenH - 402) 
  topT = one.screenH - 402 - 1; 
}; 
var top_mousedown = function (e) { 
 if (e.button > 0) { 
  top_mouseup(); 
  return false; 
 } 
 downX = e.clientX; 
 downY = e.clientY; 
 oldL = one.main.offsetLeft; 
 oldT = one.main.offsetTop; 
 AddEvent2(document, EventsType[2], top_mouseup, EventsType[5], doc_top_mousemove); 
}; 
var doc_top_mousemove = function (e) { 
 topL = oldL + e.clientX - downX; 
 topT = oldT + e.clientY - downY; 
 topLimit(); 
 setLT(one.main, topL, topT); 
}; 
var top_mouseup = function () { 
 DelEvent2(document, EventsType[2], top_mouseup, EventsType[5], doc_top_mousemove); 
}; 
/* one.top Events end */ 

/* one.movebox Events start */ 
var moveboxLimit = function () { 
 if (moveboxL <= moveboxMinL) 
  moveboxL = moveboxMinL; 
 else if (moveboxL >= moveboxMaxL) 
  moveboxL = moveboxMaxL; 
 if (moveboxT <= moveboxMinT) 
  moveboxT = moveboxMinT; 
 else if (moveboxT > moveboxMaxT) 
  moveboxT = moveboxMaxT; 
}; 
var movebox_mousedown = function (e) { 
 if (e.button > 0) { 
  movebox_mouseup(); 
  return false; 
 } 
 e.preventDefault && e.preventDefault(); 
 downX = e.clientX; 
 downY = e.clientY; 
 oldL = moveboxL; 
 oldT = moveboxT; 
 AddEvent2(document, EventsType[2], movebox_mouseup, EventsType[5], doc_movebox_mousemove); 
}; 
var doc_movebox_mousemove = function (e) { 
 moveboxL = oldL + e.clientX - downX; 
 moveboxT = oldT + e.clientY - downY; 
 moveboxLimit(); 
 setLT(one.movebox, moveboxL, moveboxT); 
 fun.setimg(); 
 fun.set_dxx(); 
}; 
var movebox_mouseup = function () { 
 DelEvent2(document, EventsType[2], movebox_mouseup, EventsType[5], doc_movebox_mousemove); 
}; 
/* one.movebox Events end */ 

/* 拉伸事件开始 */ 
var TopLeft_mousedown = function (e) { 
 if (e.button > 0) { 
  TopLeft_mouseup(); 
  return false; 
 } 
 e.preventDefault && e.preventDefault(); 
 downX = e.clientX; 
 downY = e.clientY; 
 oldL = moveboxL; 
 oldT = moveboxL; 
 tempWH = moveboxWH; 
 tempL = moveboxL - bigimgL; 
 tempT = moveboxT - bigimgT; 
 tempMaxL = moveboxMaxL; 
 tempMaxT = moveboxMaxT; 
 dxMax = tempL >= tempT ? tempT : tempL; 
 AddEvent2(document, EventsType[2], TopLeft_mouseup, EventsType[5], doc_TopLeft_mousemove); 
}; 
var doc_TopLeft_mousemove = function (e) { 
 movebox_mouseup();//移动事件屏蔽,非常重要 
 var dx = e.clientY - downY; 
 if (dx < 0 && Math.abs(dx) > dxMax) { 
  dx = -dxMax; 
 } 
 else if (dx > 0 && dx > tempWH - pic.pwh_min) { 
  dx = tempWH - pic.pwh_min; 
 } 
 moveboxMaxL = tempMaxL + dx; 
 moveboxMaxT = tempMaxT + dx; 
 moveboxL = oldL + dx; 
 moveboxT = oldT + dx; 
 moveboxWH = tempWH - dx; 
 setLT(one.movebox, moveboxL, moveboxT);  
 setWH(one.movebox, moveboxWH , moveboxWH); 
 fun.setimg(); 
 fun.set_dxx(); 
}; 
var TopLeft_mouseup = function () { 
 DelEvent2(document, EventsType[2], TopLeft_mouseup, EventsType[5], doc_TopLeft_mousemove); 
}; 

var TopRight_mousedown = function (e) { 
 if (e.button > 0) { 
  TopRight_mouseup(); 
  return false; 
 } 
 e.preventDefault && e.preventDefault(); 
 downX = e.clientX; 
 downY = e.clientY; 
 oldL = moveboxL; 
 oldT = moveboxL; 
 tempWH = moveboxWH; 
 tempL = imgW - (moveboxL - bigimgL) - moveboxWH; 
 tempT = moveboxT - bigimgT; 
 tempMaxL = moveboxMaxL; 
 tempMaxT = moveboxMaxT; 
 dxMax = tempL >= tempT ? tempT : tempL; 
 AddEvent2(document, EventsType[2], TopRight_mouseup, EventsType[5], doc_TopRight_mousemove); 
}; 
var doc_TopRight_mousemove = function (e) { 
 movebox_mouseup();//移动事件屏蔽,非常重要 
 var dx = e.clientY - downY; 
 if (dx < 0 && Math.abs(dx) > dxMax) { 
  dx = -dxMax; 
 } 
 else if (dx > 0 && dx > tempWH - pic.pwh_min) { 
  dx = tempWH - pic.pwh_min; 
 } 
 moveboxMaxL = tempMaxL + dx; 
 moveboxMaxT = tempMaxT + dx; 
 moveboxL = oldL; 
 moveboxT = oldT + dx; 
 moveboxWH = tempWH - dx; 
 setLT(one.movebox, moveboxL, moveboxT); 
 setWH(one.movebox, moveboxWH, moveboxWH); 
 fun.setimg(); 
 fun.set_dxx(); 
}; 
var TopRight_mouseup = function () { 
 DelEvent2(document, EventsType[2], TopRight_mouseup, EventsType[5], doc_TopRight_mousemove); 
}; 

var BottomRight_mousedown = function (e) { 
 if (e.button > 0) { 
  BottomRight_mouseup(); 
  return false; 
 } 
 e.preventDefault && e.preventDefault(); 
 downX = e.clientX; 
 downY = e.clientY; 
 oldL = moveboxL; 
 oldT = moveboxL; 
 tempWH = moveboxWH; 
 tempL = imgW - (moveboxL - bigimgL) - moveboxWH; 
 tempT = imgH - (moveboxT - bigimgT) - moveboxWH; 
 tempMaxL = moveboxMaxL; 
 tempMaxT = moveboxMaxT; 
 dxMax = tempL >= tempT ? tempT : tempL; 
 AddEvent2(document, EventsType[2], BottomRight_mouseup, EventsType[5], doc_BottomRight_mousemove); 
}; 
var doc_BottomRight_mousemove = function (e) { 
 movebox_mouseup();//移动事件屏蔽,非常重要 
 var dx = e.clientY - downY; 
 if (dx > 0 && dx > dxMax) { 
  dx = dxMax; 
 } 
 else if (dx < 0 && Math.abs(dx) > tempWH - pic.pwh_min) { 
  dx = -(tempWH - pic.pwh_min); 
 } 
 moveboxMaxL = tempMaxL - dx; 
 moveboxMaxT = tempMaxT - dx; 
 moveboxL = oldL; 
 moveboxT = oldT; 
 moveboxWH = tempWH + dx; 
 setLT(one.movebox, moveboxL, moveboxT); 
 setWH(one.movebox, moveboxWH, moveboxWH); 
 fun.setimg(); 
 fun.set_dxx(); 
}; 
var BottomRight_mouseup = function () { 
 DelEvent2(document, EventsType[2], BottomRight_mouseup, EventsType[5], doc_BottomRight_mousemove); 
}; 

var BottomLeft_mousedown = function (e) { 
 if (e.button > 0) { 
  BottomLeft_mouseup(); 
  return false; 
 } 
 e.preventDefault && e.preventDefault(); 
 downX = e.clientX; 
 downY = e.clientY; 
 oldL = moveboxL; 
 oldT = moveboxL; 
 tempWH = moveboxWH; 
 tempL = moveboxL - bigimgL; 
 tempT = imgH - (moveboxT - bigimgT) - moveboxWH; 
 tempMaxL = moveboxMaxL; 
 tempMaxT = moveboxMaxT; 
 dxMax = tempL >= tempT ? tempT : tempL; 
 AddEvent2(document, EventsType[2], BottomLeft_mouseup, EventsType[5], doc_BottomLeft_mousemove); 
}; 
var doc_BottomLeft_mousemove = function (e) { 
 movebox_mouseup();//移动事件屏蔽,非常重要 
 var dx = e.clientY - downY; 
 if (dx > 0 && dx > dxMax) { 
  dx = dxMax; 
 } 
 else if (dx < 0 && Math.abs(dx) > tempWH - pic.pwh_min) { 
  dx = -(tempWH - pic.pwh_min); 
 } 
 moveboxMaxL = tempMaxL - dx; 
 moveboxMaxT = tempMaxT - dx; 
 moveboxL = oldL - dx; 
 moveboxT = oldT; 
 moveboxWH = tempWH + dx; 
 setLT(one.movebox, moveboxL, moveboxT); 
 setWH(one.movebox, moveboxWH, moveboxWH); 
 fun.setimg(); 
 fun.set_dxx(); 
}; 
var BottomLeft_mouseup = function () { 
 DelEvent2(document, EventsType[2], BottomLeft_mouseup, EventsType[5], doc_BottomLeft_mousemove); 
}; 
/* 拉伸事件结束 */ 

/* 两个按钮事件开始 */ 
var callback = function () { 
 var txt = xmlReq.responseText; 
 one.avatar_img.src = "../saveimg/"+txt; 
 Hide(one.main); 
 Show(one.avatar); 
}; 
var create_msg = function () { 
 var msg = "moveboxL=" + (moveboxL - bigimgL) + "&moveboxT=" + (moveboxT - bigimgT) + "&moveboxWH=" + moveboxWH; 
 msg += "&imgURL=" + imgURL; 
 return msg; 
}; 
var p2_click = function () { 
 url="../Avatar/AJAX_saveimg"; 
 method = "post"; 
 msg = create_msg(); 
 AJAX(url, method, msg, callback); 
}; 
var p3_click = function () { 
 Hide(one.main); 
 Show(one.avatar); 
}; 
/* 两个按钮事件结束 */ 
var Events = function () { 
 AddEvent3(one.avatar, EventsType[0], avatar_click, EventsType[3], avatar_mouseover, EventsType[4], avatar_mouseleave);//avatar 
 AddEvent(one.top, EventsType[1], top_mousedown);//top 
 AddEvent(one.movebox, EventsType[1], movebox_mousedown);//movebox 
 AddEvent(one.TopLeft, EventsType[1], TopLeft_mousedown);//TopLeft 
 AddEvent(one.TopRight, EventsType[1], TopRight_mousedown);//TopRight 
 AddEvent(one.BottomRight, EventsType[1], BottomRight_mousedown);//BottomRight 
 AddEvent(one.BottomLeft, EventsType[1], BottomLeft_mousedown);//BottomLeft 
 AddEvent(one.p2, EventsType[0], p2_click);//p2 
 AddEvent(one.p3, EventsType[0], p3_click);//p3 
 /* =========================================== END =========================================== */ 
 AddEvent(document, EventsType[5], cannotselect);//最后添加整个页面无法选中事件 
}; 

def.js

var pic = { 
 pwh_max: 299, //图片最大宽高 
 pwh_min: 30,  //图片最小宽高 
 P:10/1,   //图片宽高比 
 movediv_min: 30, //截框最小宽高 
 movediv_default: 100,//截框初始宽高 
 W_H: false, //宽大于高? 
 imgtype: ["image/jpeg", "image/png", "image/gif", "image/bmp"],//支持这4种类型图片 
 imgsize: 5 * 1024 * 1024, //最大5M 
 d11WH: 119, 
 d22WH: 99, 
 d33WH: 71, 
 URL:window.URL || window.webkitURL || window.mozURL || window.msURL || false, 
}; 
var fun = { 
 FormBlob: function (dataURI) { 
  var byteString, splits = false, splits1 = dataURI.replace(new RegExp("^data:.*base64,"), function () { 
   splits = true; 
   return ""; 
  }); 
  byteString = atob(splits1); 
  var byteStringlength = byteString.length, ia = new Uint8Array(byteStringlength); 
  for (var i = 0; i < byteStringlength; i++) { 
   ia[i] = byteString.charCodeAt(i); 
  } 
  return new Blob([ia], { 
   type: imgtype 
  }); 
 }, 
 check_imgtype: function () { 
  if (!inArray(imgtype, pic.imgtype)) { 
   one.upfile.parentNode.removeChild(one.upfile); 
   alert("请选择正确的图片类型"); 
   return false; 
  } else { return true;} 
 }, 
 check_imgsize: function () { 
  if (imgsize > pic.imgsize) { 
   this.parentNode.removeChild(this); 
   alert("图片不能超过5M"); 
   return false; 
  } else { return true;} 
 }, 
 setImgWH: function (src,type) { 
  var image = new Image(); 
  image.onload = function () { 
   var newcanvas = document.createElement("canvas"); 
   newcanvas.style.display = "none"; 
   var bodys = document.body; 
   bodys.appendChild(newcanvas); 
   var ctx = newcanvas.getContext("2d"); 
   var width = this.width, height = this.height;//图片的宽高 
   var w, h; //选取图片的宽高 
   var cw, ch;//画布的宽高 
   var P = width / height; 
   imgP = P; 
   pic.W_H = width > height ? true : false; 
   if (pic.W_H) { 
    if (P >= 10) { 
     ch = pic.pwh_min; 
     cw = pic.pwh_max; 
     h = height; 
     w = h * pic.pwh_max / pic.pwh_min; 
    } 
    else { 
     if (height <= pic.pwh_min) { 
      ch = pic.pwh_min; 
      cw = Math.round(ch * P); 
      h = height; 
      w = width; 
     } 
     else if (width >= pic.pwh_max) { 
      cw = pic.pwh_max; 
      ch = Math.round(cw / P); 
      h = height; 
      w = width; 
     } 
     else { 
      cw = width; 
      ch = height; 
      h = height; 
      w = width; 
     } 
    } 
   } 
   else { 
    if (P <= 1 / 10) { 
     cw = pic.pwh_min; 
     ch = pic.pwh_max; 
     w = width; 
     h = w * pic.pwh_max / pic.pwh_min; 
    } 
    else { 
     if (width <= pic.pwh_min) { 
      cw = pic.pwh_min; 
      ch = Math.round(cw / P); 
      w = width; 
      h = height; 
     } 
     else if (height >= pic.pwh_max) { 
      ch = pic.pwh_max; 
      cw = Math.round(ch * P); 
      w = width; 
      h = height; 
     } 
     else { 
      cw = width; 
      ch = height; 
      h = height; 
      w = width; 
     } 
    } 
   } 
   ///////////////////////////////////////////////////// 
   imgW = newcanvas.width = cw; 
   imgH = newcanvas.height = ch; 
   ctx.fillStyle = "#FFFFFF"; 
   ctx.fillRect(0, 0, cw, ch); 
   ctx.drawImage(image, 0, 0, w, h, 0, 0,cw, ch); 
   imgURL = newcanvas.toDataURL(type, 1); 
   //imgURL = pic.URL.createObjectURL(fun.FormBlob(imgURL)); 
   one.d11.src = one.d22.src = one.d33.src = one.bigimg.src = one.moveimg.src = imgURL; 
   ctx.clearRect(0, 0, cw, ch); 
   bodys.removeChild(newcanvas); 
   delete DATA; 
   delete image; 
   fun.setStart(); 
  }; 
  image.onerror = function () { 
   alert("图片已损坏,请上传正确图片"); 
  }; 
  image.src = src; 
 }, 
 setStart: function () { 
  Hide(one.avatar); 
  Show(one.main); 
  fun.set_bigimg(); 
  fun.set_movebox(); 
  fun.set_dxx(); 
 }, 
 set_bigimg: function () { 
  bigimgL = Math.round((pic.pwh_max - imgW) / 2); 
  bigimgT = Math.round((pic.pwh_max - imgH) / 2); 
  setLT(one.bigimg,bigimgL,bigimgT); 
 }, 
 set_movebox: function () { 
  if (pic.W_H) { 
   moveboxWH = imgH <= pic.movediv_default ? imgH : pic.movediv_default; 
  } 
  else { 
   moveboxWH = imgW <= pic.movediv_default ? imgW : pic.movediv_default; 
  } 
  moveboxL = Math.round((pic.pwh_max - moveboxWH) / 2); 
  moveboxT = Math.round((pic.pwh_max - moveboxWH) / 2); 
  moveboxMinL = bigimgL; 
  moveboxMinT = bigimgT; 
  moveboxMaxL = Math.round(pic.pwh_max - moveboxWH - bigimgL); 
  moveboxMaxT = Math.round(pic.pwh_max - moveboxWH - bigimgT); 
  setLT(one.movebox, moveboxL, moveboxT); 
  setWH(one.movebox, moveboxWH, moveboxWH); 
  moveimgL = -Math.round((imgW - moveboxWH) / 2); 
  moveimgT = -Math.round((imgH - moveboxWH) / 2); 
  setLT(one.moveimg, moveimgL, moveimgT); 
 }, 
 set_dxx: function () { 
  var P1 = pic.d11WH / moveboxWH; 
  var P2 = pic.d22WH / moveboxWH; 
  var P3 = pic.d33WH / moveboxWH;  
  var d11W = Math.round(imgW * P1); 
  var d22W = Math.round(imgW * P2); 
  var d33W = Math.round(imgW * P3); 
  var d11H = Math.round(imgH * P1); 
  var d22H = Math.round(imgH * P2); 
  var d33H = Math.round(imgH * P3); 
  setWH(one.d11, d11W, d11H); 
  setWH(one.d22, d22W, d22H); 
  setWH(one.d33, d33W, d33H); 
  var d11L = Math.round(moveimgL * P1); 
  var d22L = Math.round(moveimgL * P2); 
  var d33L = Math.round(moveimgL * P3); 
  var d11T = Math.round(moveimgT * P1); 
  var d22T = Math.round(moveimgT * P2); 
  var d33T = Math.round(moveimgT * P3); 
  setLT(one.d11, d11L, d11T); 
  setLT(one.d22, d22L, d22T); 
  setLT(one.d33, d33L, d33T); 
 }, 
 setimg: function () { 
  moveimgL = bigimgL - one.movebox.offsetLeft; 
  moveimgT = bigimgT - one.movebox.offsetTop; 
  setLT(one.moveimg, moveimgL, moveimgT); 
 }, 
}; 

Index.cshtml

<!DOCTYPE html> 
<html> 
<head> 
 <meta name="viewport" content="width=device-width" /> 
 <script src="~/Scripts/one.js"></script> 
 <script src="~/Scripts/Events.js"></script> 
 <script src="~/Scripts/def.js"></script> 
 <script src="~/Scripts/cxc.js"></script> 
 <link href="~/Content/Avatar_Main.css" rel="stylesheet" /> 
 <title>@ViewBag.Title</title> 
</head> 
<body> 
 <div id="avatar"> 
  <img id="avatar_img" src="~/Images/default_avatar.jpg" /> 
 </div> 

 <div id="main"> 
  <div id="top"> 
   <p id="p1"> 图 片 截 取 </p> 
  </div> 
  <div id="center"> 
   <div id="movebox"> 
    <i id="TopLeft"></i> 
    <i id="TopRight"></i> 
    <i id="BottomRight"></i> 
    <i id="BottomLeft"></i> 
    <img id="moveimg"/> 
   </div> 
   <div id="black"></div> 
   <img id="bigimg"/> 
  </div> 

  <div id="d1"> 
   <img id="d11"/> 
  </div> 
  <div id="d2"> 
   <img id="d22"/> 
  </div> 
  <div id="d3"> 
   <img id="d33"/> 
  </div> 
  <div id="bottom"> 
   <p id="p2">就是它了</p> 
   <p id="p3">暂且放弃</p> 
  </div> 
 </div> 
</body> 
</html> 

Avatar_Main.css

body { 
 margin:0px; 
 padding:0px; 
 background-color:#9C938F; 
} 
#avatar{ 
 width:120px; 
 height:120px; 
 border:2px solid #FFFFFF; 
 position:absolute;  
 top:30px; 
 left:8%; 
 border-radius:7px; 
 background-color:#ffffff; 
 overflow:hidden; 
 cursor:pointer; 
} 
#avatar_img{ 
 width:120px; 
 height:120px; 
} 
#upfile{ 
 display:none; 
} 
#main{ 
 position:absolute; 
 width:430px; 
 height:400px; 
 background-color:#9C938F; 
 border-bottom:1px solid #fff; 
 border-right:1px solid #fff; 
 border-left:1px solid #635E5B; 
 border-top:1px solid #635E5B; 
 border-radius:8px; 
} 
#top,#center,#d1,#d2,#d3,#bottom{ 
 position:absolute; 
 border-bottom:1px solid #635E5B; 
 border-right:1px solid #635E5B; 
 border-left:1px solid #fff; 
 border-top:1px solid #fff; 
 background-color:#9C938F; 
 border-radius:8px; 
} 
#top{ 
 width:424px; 
 height:43px; 
 left:2px; 
 top:2px; 
 text-align: center;  
 cursor:move; 
} 
#p1{ 
 position:absolute; 
 left:115px; 
 top:-30px; 
 font-size:30px; 
 font-family:"微软雅黑"; 
 color: #9C938F; 
 font-weight:normal; 
 text-shadow: -1px -1px white, 1.2px 1.2px #333333; 
} 
#center{ 
 width:300px; 
 height:300px; 
 top:49px; 
 left:2px; 
 overflow:hidden; 
 border-radius:0px; 
} 
#d1{ 
 overflow:hidden; 
 width:120px; 
 height:120px; 
 top:49px; 
 right:2px; 
 border-radius:0px; 
} 
#d2{ 
 overflow:hidden; 
 width:100px; 
 height:100px; 
 top:173px; 
 right:2px; 
 border-radius:0px; 
} 
#d3{ 
 overflow:hidden; 
 width:72px; 
 height:72px; 
 top:277px; 
 right:2px; 
 border-radius:0px; 
} 
#bottom{ 
 width:424px; 
 height:43px; 
 left:2px; 
 bottom:2px; 
} 
#p2,#p3{ 
 position:absolute; 
 width:100px; 
 height:30px; 
 font-size:22px; 
 font-family:"微软雅黑"; 
 color: #9C938F; 
 font-weight:normal; 
 text-shadow: -1px -1px white, 1.2px 1.2px #333333; 
} 
#p2:hover,#p3:hover{ 
 cursor:pointer; 
 color:#bbbbbb; 
} 
#p2{ 
 top:-15px; 
 left:200px; 
} 
#p3{ 
 top:-15px; 
 right:10px; 
} 
#bigimg{ 
 position:absolute; 
} 
#black{ 
 position:absolute; 
 z-index:99; 
 width:299px; 
 height:299px; 
 background-color:#000; 
 opacity:0.6; 
} 
#movebox { 
 position: absolute; 
 z-index: 100; 
 overflow: hidden; 
 cursor:move; 
} 

#BottomRight,#TopRight,#TopLeft,#BottomLeft { 
 background:#D6FB66; 
 display:block; 
 width:6px; 
 height:6px; 
 overflow:hidden; 
 position:absolute; 
 z-index:105; 
 bottom:0; 
 right:0; 
 cursor:nw-resize; 
} 
#BottomLeft { 
 bottom:0; 
 left:0; 
 cursor:ne-resize; 
} 
#TopRight { 
 top:0; 
 right:0; 
 cursor:ne-resize; 
} 
#TopLeft { 
 top:0; 
 left:0; 
 cursor:nw-resize; 
} 
#moveimg{ 
 position:absolute; 
} 
#d11,#d22,#d33{ 
 position:absolute; 
} 

以上就是本文的全部内容,希望对大家学习javascript程序设计有所帮助。

您可能感兴趣的文章:

  • 针对多用户实现头像上传功能PHP代码 适用于登陆页面制作
  • 全屏js头像上传插件源码高清版
  • php视频拍照上传头像功能实现代码分享
  • 实现Asp.net mvc上传头像加剪裁功能
  • Android实现本地上传图片并设置为圆形头像
  • PHP+ajaxfileupload+jcrop插件完美实现头像上传剪裁
  • JS仿flash上传头像效果实现代码
  • 关于js拖拽上传 [一个拖拽上传修改头像的流程]
  • php+js iframe实现上传头像界面无跳转
  • web前端开发upload上传头像js示例代码

编辑:编程 本文来源:需要用到头像上传的功能,前端页面设计

关键词: