首页 > 代码库 > java web 站点头像上传处理 (springmvc +bootstrap+cropper)

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

制作头像上传。请依据您的实际需求。改动代码,不全然正确。仅供參考!

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

后台使用springmvc。


如今来看前端的页面设计

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

剪裁效果图



技术分享




html 文件

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>cropper</title>
    <link href=http://www.mamicode.com/"css/bootstrap.css" rel="stylesheet"/>>

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 = http://www.mamicode.com/$image.cropper('getCropBoxData');>
须要加入的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的。关于图像处理的。就是我个人做的。好像网上有直接在前端进行剪裁的,可惜我不会啊,所以我还是老老实实的在后台处理了。

<strong>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=http://www.mamicode.com/"/updateuserlogo")>

以下是图像处理的工具类。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<ImageReader> 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<ImageReader> 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<ImageReader> 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<ImageReader> 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 = http://www.mamicode.com/ImageIO.read(new File(srcImageFile)); // 读入文件>

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 = http://www.mamicode.com/ImageIO.read(new File(srcImageFile)); >

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 = http://www.mamicode.com/ImageIO.read(file); // 读入文件>


制作头像上传。

请依据您的实际需求,改动代码。不全然正确,仅供參考。

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

后台使用springmvc。


如今来看前端的页面设计

前端页面设计,自然须要bootstrap 、jqury 和cropper 。这能够自行去网上百度查找

剪裁效果图


html 文件

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>cropper</title>
    <link href=http://www.mamicode.com/"css/bootstrap.css" rel="stylesheet"/>>

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 = http://www.mamicode.com/$image.cropper('getCropBoxData');>
须要加入的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的,关于图像处理的。就是我个人做的。好像网上有直接在前端进行剪裁的,可惜我不会啊,所以我还是老老实实的在后台处理了。

<strong>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=http://www.mamicode.com/"/updateuserlogo")>

以下是图像处理的工具类。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<ImageReader> 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<ImageReader> 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<ImageReader> 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<ImageReader> 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 = http://www.mamicode.com/ImageIO.read(new File(srcImageFile)); // 读入文件>

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 = http://www.mamicode.com/ImageIO.read(new File(srcImageFile)); >

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 = http://www.mamicode.com/ImageIO.read(file); // 读入文件>

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