工具类-图片压缩


import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;

import javax.imageio.ImageIO;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.xqx.gzpt.util.AES.AESImageUtil;

import net.coobird.thumbnailator.Thumbnails;

/**
 * 
 *  
 * <p>描述: 压缩图片工具类</p>  
 *
 * @author Wtao  
 * @date 2018年11月7日
 */
public class ImageZoom {

    private static Logger logger = LoggerFactory.getLogger(ImageZoom.class);
	
	/**
     * 按指定高度 等比例缩放图片
     * 
     * @param imageFile
     * @param newPath
     * @param newWidth 新图的宽度
	 * @throws Exception 
     */
    public static void zoomImageScale(MultipartFile multipartFile, int newWidth,String savePath) throws Exception {
    	if(Validator.isNull(multipartFile)){
    		logger.debug("压缩图片出错!未获取到上传的图片!");
    		throw new RuntimeException("压缩图片并加密时报错,出错原因:multipartFile 为 null !"); 
    	}
    	InputStream imageInputStream = multipartFile.getInputStream();	
    	String format = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1, multipartFile.getOriginalFilename().length());   	
        zoomImageUtils(imageInputStream, newWidth, format, savePath); 		
    }
    
    public static void zoomImageFromByte(byte[] b , int newWidth,String savePath,String format) throws Exception {
    	if(Validator.isNull(b)){
    		logger.debug("压缩图片出错!未获取到上传的图片!");
    		throw new RuntimeException("压缩图片并加密时报错,出错原因:b 为 null !"); 
    	}
    	InputStream imageInputStream = new ByteArrayInputStream(b);
        zoomImageUtils(imageInputStream, newWidth, format, savePath);      
    }
    
    /**
     * 
     * @param bufferedImage BufferedImage对象
     * @param newWidth 新的宽度
     * @param format 文件格式
     * @param savePath 文件保存路径
     * @throws Exception 
     */
    public static void zoomImageUtils(InputStream imageInputStream,int newWidth,String format,String savePath) throws Exception{
    	if(Validator.isNull(imageInputStream)){
      		logger.debug("压缩图片出错!未获取到上传的图片!");
      		throw new RuntimeException("压缩图片并加密时报错,出错原因:imageInputStream 为 null !"); 
      	}
    	ByteArrayOutputStream outputStream = null;
      	ByteArrayInputStream swapStream = null;
      	InputStream is = null;
      	ByteArrayOutputStream os = null;
      	try {
      		BufferedImage bufferedImage = ImageIO.read(imageInputStream);     
      		outputStream = new ByteArrayOutputStream();
      		os = new ByteArrayOutputStream(); 
	    	int originalWidth = bufferedImage.getWidth();//原始宽  
	        int originalHeight = bufferedImage.getHeight();//原始高 	        
	        ImageIO.write(bufferedImage, format, os);  
	        is = new ByteArrayInputStream(os.toByteArray());
	        float scale = 0.0f;
	        if(originalWidth < originalHeight){
	        	scale = new BigDecimal(newWidth).divide(new BigDecimal(originalHeight),2, BigDecimal.ROUND_HALF_EVEN).setScale(2).floatValue();
	        }else {
	        	scale = new BigDecimal(newWidth).divide(new BigDecimal(originalWidth), 2,BigDecimal.ROUND_HALF_EVEN).setScale(2).floatValue();
			}
	        if(scale >= 1){
	        	scale = 1;
	        }
	        
	        Thumbnails.of(is)
			.scale(scale) 
			.outputQuality(0.9f).toOutputStream(outputStream);
			//.toFile("E:\\加密前备份\\W201709050065\\test001.JPG");
	        if(Validator.isNull(outputStream)){
	     	   logger.debug("压缩图片出错!");
	     	   throw new RuntimeException("压缩图片并加密时报错,出错原因:baos 为 null !"); 
	        }else{
	        	swapStream = new ByteArrayInputStream(outputStream.toByteArray());     
	       	    try {
	 				//加密图片并保存
	 				AESImageUtil.EncryptFromStram(swapStream, savePath,AESImageUtil.secretKey);
	 			} catch (Exception e) {
	 				logger.debug("加密图片出错:图片是"+savePath);
	 				e.printStackTrace();
	 				throw new RuntimeException("加密图片出错:图片是"+savePath); 
	 			}  			 			
	        }
      	}catch(Exception e) {
      		throw e;
      	}finally{
			if(outputStream != null){
				outputStream.close();
			}
			if(swapStream != null){
				swapStream.close();
			}
			if(is != null ){
				is.close();
			}
			if(os != null){
				os.close();
			}
			if(imageInputStream != null){
				imageInputStream.close();
			}			
      	}
 		
    }
    

    /**
     * 等比例改变图片尺寸
     * @param nw 新图片的宽度
     * @param oldImage 原图片
     * @throws IOException
     */
    public static void constrainProportios(int nw, String oldImage) throws IOException {
        AffineTransform transform = new AffineTransform();
        BufferedImage bis = ImageIO.read(new File(oldImage));
        int w = bis.getWidth();
        int h = bis.getHeight();
        int nh = (nw * h) / w;
        double sx = (double) nw / w;
        double sy = (double) nh / h;
        transform.setToScale(sx, sy);
        AffineTransformOp ato = new AffineTransformOp(transform, null);
        BufferedImage bid = new BufferedImage(nw, nh, BufferedImage.TYPE_3BYTE_BGR);
        ato.filter(bis, bid);
        
        String newPath = StringUtils.substringBeforeLast(oldImage,".")+"_3."+StringUtils.substringAfterLast(oldImage,".");
        ImageIO.write(bid, "jpeg", new File(newPath));
    }

}

猜你喜欢

转载自blog.csdn.net/RUANJIAOXIAOZI/article/details/83824782