图片等比控制

 

JSP:
<div class="modal-body upload-box">
	<div class="upload-header">
		<a href="javascript:;" class="btn btn-orange btn_chooseImg" ><i class="fa fa-image"></i>选择图片</a>
		<span class="imgNameLabel" style="display: none;">请选择..</span>
		<!--选择文件-->
		<input type="file" name="imgfileInput" id="imgfileInput" class="imgfileInput"  accept=".jpg,.png,.gif" style="display: none;" >
		<!--上传文件的路径-->
		<input type="hidden" name="signaturePicPath" id="signaturePicPath" class="dfinput imgInput"/>
	</div>
	<div class="upload-body" style="height: 100px;width: 100px;">
		<!--图片回显-->
		<img src="" id="img_Box" class="img_Box" style="width:100%;"/>
	</div>
</div>
JAVA:
@RequestMapping(value = "/uploadimage")
	public void uploadImage(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 获取文件保存路径
		Map<String, String> absPath = initializeData.getPicUploadUrl();
		// 绝对路径
		String path = absPath.get("picUrl");
		String size = absPath.get("picSize");
		String type = absPath.get("picType");
		String relpath = "/avatar";
		String finalPath = path + relpath;
		// 转型为MultipartHttpRequest:
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 获得文件:
		Map<String, MultipartFile> files = multipartRequest.getFileMap();
		Iterator<String> iterator = files.keySet().iterator();
		MultipartFile file = null;
		while (iterator.hasNext()) {
			String key = iterator.next();
			file = files.get(key);
		}
		String imageType = file.getContentType();
		type = type == null ? "jpeg,png,gif,jpg" : type;
		String[] types = type.split(",");
		boolean flag = false;
		for (String arg : types) {
			if (imageType.contains(arg)) {
				flag = true;
			}
		}
		if (!flag) {
			// 状态
			resultMap.put("state", FAIL);
			resultMap.put("message", "图片类型不符合");
			super.commonJSONResponse(resultMap, response);
			return;
		}
		// 获得文件名
		String fileName = file.getOriginalFilename();
		// 创建文件夹
		File dirPath = new File(finalPath);
		if (!dirPath.exists()) {
			dirPath.mkdirs();
		}
		// 创建文件
		File uploadFile = new File(finalPath + "/" + fileName);
		// Copy文件
		FileCopyUtils.copy(file.getBytes(), uploadFile);
		String scaling = size == null ? "10|20,20|30,30|40,40|50,50|60"
				: (String) customSource.get(Constant.SCALING);
		String[] imageSize = scaling.split(",");
		for (int i = 0; i < imageSize.length; i++) {
			String[] fileSize = imageSize[i].split("\\|");
			int targetWidth = Integer.valueOf(fileSize[0]);
			int targetHeight = Integer.valueOf(fileSize[1]);
			// 缩放保存
			String oldPath = finalPath + "/" + fileName;
			// 处理后的图片名及路径
			int index = fileName.indexOf(".");
			String newFileName = fileName.substring(0, index) + "_" + (i + 1)
					+ fileName.substring(index, fileName.length());
			String newPath = finalPath + "/" + newFileName;
			ImageUtils.scale2(oldPath, newPath, targetHeight, targetWidth,
					false);
		}
		// 状态
		resultMap.put("state", SUCCESS);
		// 地址
		resultMap.put("url", fileName);
		super.commonJSONResponse(resultMap, response);
	}



ImageUtils:

package com.bs.utils;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageUtils {
	/**
	 * 对图片进行放大
	 * 
	 * @param originalImage
	 *            原始图片
	 * @param times
	 *            放大倍数
	 * @return
	 */
	public static BufferedImage zoomInImage(BufferedImage originalImage,Integer times){
		int width = originalImage.getWidth() * times;
		int height = originalImage.getHeight() * times;
		BufferedImage newImage = new BufferedImage(width,height,originalImage.getType());
		Graphics g = newImage.getGraphics();
		g.drawImage(originalImage,0,0,width,height,null);
		g.dispose();
		return newImage;
	}

	/**
	 * 对图片进行放大
	 * 
	 * @param srcPath
	 *            原始图片路径(绝对路径)
	 * @param newPath
	 *            放大后图片路径(绝对路径)
	 * @param times
	 *            放大倍数
	 * @return 是否放大成功
	 */
	public static boolean zoomInImage(String srcPath,String newPath,Integer times){
		BufferedImage bufferedImage = null;
		try{
			File of = new File(srcPath);
			if(of.canRead()){
				bufferedImage = ImageIO.read(of);
			}
		}
		catch(IOException e){
			// TODO: 打印日志
			return false;
		}
		if(bufferedImage != null){
			bufferedImage = zoomInImage(bufferedImage,times);
			try{
				// TODO: 这个保存路径需要配置下子好一点
				ImageIO.write(bufferedImage,"JPG",new File(newPath)); // 保存修改后的图像,全部保存为JPG格式
			}
			catch(IOException e){
				// TODO 打印错误信息
				return false;
			}
		}
		return true;
	}

	/**
	 * 对图片进行缩小
	 * 
	 * @param originalImage
	 *            原始图片
	 * @param times
	 *            缩小倍数
	 * @return 缩小后的Image
	 */
	public static BufferedImage zoomOutImage(BufferedImage originalImage,Integer times){
		int width = originalImage.getWidth() / times;
		int height = originalImage.getHeight() / times;
		BufferedImage newImage = new BufferedImage(width,height,originalImage.getType());
		Graphics g = newImage.getGraphics();
		g.drawImage(originalImage,0,0,width,height,null);
		g.dispose();
		return newImage;
	}

	/**
	 * 对图片进行缩小
	 * 
	 * @param srcPath
	 *            源图片路径(绝对路径)
	 * @param newPath
	 *            新图片路径(绝对路径)
	 * @param times
	 *            缩小倍数
	 * @return 保存是否成功
	 */
	public static boolean zoomOutImage(String srcPath,String newPath,Integer times){
		BufferedImage bufferedImage = null;
		try{
			File of = new File(srcPath);
			if(of.canRead()){
				bufferedImage = ImageIO.read(of);
			}
		}
		catch(IOException e){
			// TODO: 打印日志
			return false;
		}
		if(bufferedImage != null){
			bufferedImage = zoomOutImage(bufferedImage,times);
			try{
				// TODO: 这个保存路径需要配置下子好一点
				ImageIO.write(bufferedImage,"JPG",new File(newPath)); // 保存修改后的图像,全部保存为JPG格式
			}
			catch(IOException e){
				// TODO 打印错误信息
				return false;
			}
		}
		return true;
	}

	/**
	 * <b>function:</b> 通过目标对象的大小和标准(指定)大小计算出图片缩小的比例
	 * 
	 * @author hoojo
	 * @createDate 2012-2-6 下午04:41:48
	 * @param targetWidth
	 *            目标的宽度
	 * @param targetHeight
	 *            目标的高度
	 * @param standardWidth
	 *            标准(指定)宽度
	 * @param standardHeight
	 *            标准(指定)高度
	 * @return 最小的合适比例
	 */
	public static double getScaling(double targetWidth,double targetHeight,double standardWidth,double standardHeight){
		double widthScaling = 0d;
		double heightScaling = 0d;
		if(targetWidth > standardWidth){
			widthScaling = standardWidth / (targetWidth * 1.00d);
		}
		else{
			widthScaling = 1d;
		}
		if(targetHeight > standardHeight){
			heightScaling = standardHeight / (targetHeight * 1.00d);
		}
		else{
			heightScaling = 1d;
		}
		return Math.min(widthScaling,heightScaling);
	}

	/**
	 * 缩放图像(按高度和宽度缩放)
	 * 
	 * @param srcImageFile
	 *            源图像文件地址
	 * @param result
	 *            缩放后的图像地址
	 * @param height
	 *            缩放后的高度
	 * @param width
	 *            缩放后的宽度
	 * @param bb
	 *            比例不对时是否需要补白:true为补白; false为不补白; image.SCALE_SMOOTH //平滑优先 image.SCALE_FAST//速度优先 image.SCALE_AREA_AVERAGING //区域均值 image.SCALE_REPLICATE //像素复制型缩放 image.SCALE_DEFAULT //默认缩放模式
	 */
	public final static void scale2(String srcImageFile,String result,int height,int width,boolean bb){
		try{
			double ratio = 0.0; // 缩放比例
			File f = new File(srcImageFile);
			BufferedImage bi = ImageIO.read(f);
			Image itemp = bi.getScaledInstance(width,height,BufferedImage.SCALE_SMOOTH);
			// 计算比例

			if((bi.getHeight() > height) || (bi.getWidth() > width)){
				if(bi.getHeight() > bi.getWidth()){
					ratio = (new Integer(height)).doubleValue() / bi.getHeight();
				}
				else{
					ratio = (new Integer(width)).doubleValue() / bi.getWidth();
				}
				AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio,ratio),null);
				itemp = op.filter(bi,null);
			}
			else{
				// AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
				// itemp = op.filter(bi, null);
				itemp = bi;
			}
			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));
		}
		catch(IOException e){
			e.printStackTrace();
		}
	}

	public static String getNewFilePath(String filePaht,String fileSuffix){

		String path = "";
		String suffix;
		String file_name;
		int pos = filePaht.lastIndexOf("/");
		if(pos >= 0){
			file_name = filePaht.substring(pos + 1);
			path = filePaht.substring(0,pos);
		}
		else{
			file_name = filePaht;
		}
		String name = file_name.substring(0,file_name.lastIndexOf("."));
		suffix = file_name.substring(file_name.lastIndexOf("."));

		if(path != null && path.length() > 0){
			path = path + "/" + name + "_" + fileSuffix + suffix;
		}
		else{
			path = file_name + "_" + fileSuffix + suffix;

		}

		return path;

	}

}

 

 

 

转载于:https://my.oschina.net/u/2944990/blog/756461

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值