SpringMvc图片压缩上传

一个简单的图片压缩上传方法,支持按比例缩放或按尺寸强制缩放

/***
 * 
 * @param newFilePath 生成的文件路径
 * @param file SpringMvc接收到的文件
 * @param width 存储的图片的宽
 * @param height 存储的图片的高
 * @param isRatio 是否等比例缩放,true为按比例缩放,false为按固定尺寸缩放
 * @return 带路径的文件名称
 * @throws IllegalStateException
 * @throws IOException
 * @author Pcject
 */
public static String imgUploadZip(String newFilePath,MultipartFile file,int width,int height,boolean isRatio)throws IllegalStateException, IOException{
     Image img = ImageIO.read(file.getInputStream());      // 取文件流构造Image对象  
     int widthR = img.getWidth(null);    // 得到源图宽  
     int heightR = img.getHeight(null);  // 得到源图宽
     int widthW =0;
     int heightW =0;
     if(isRatio)
     {
         // 按照宽度还是高度进行压缩
          //注意几个变量都是int类型,需要加float强转,否则取整很容易都相等
         if (((float)widthR / heightR) > ((float)width / height)) {  
             heightW = (int) (heightR * width / widthR);  
             widthW = width;  
            } else {  
                 heightW = height;  
                 widthW = (int) (widthR* height / heightR);
            } 
     }
     else {
        heightW = height;
        widthW = width;
    }
        BufferedImage image = new BufferedImage(widthW, heightW,BufferedImage.TYPE_INT_RGB );   
        image.getGraphics().drawImage(img, 0, 0, widthW, heightW, null); // 绘制缩小后的图  
        String result = "";
        String name = file.getOriginalFilename();
        name = name.replace(".", ",");
        String[] str = name.split(",");//获取文件后缀名
        String fileName = TdExpBasicFunctions.GETDATETIME() +"."+str[str.length-1];
        File file2 = new File(newFilePath);
        if (!file2.exists())
            file2.mkdirs();
        String filePath = newFilePath + fileName;
        ImageIO.write(image, str[str.length-1], new File(filePath));    
        result = newFilePath + fileName;
        return result;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值