您的位置:首页 > 编程语言 > Java开发

SpringMvc图片压缩上传

2017-12-07 16:32 375 查看
一个简单的图片压缩上传方法,支持按比例缩放或按尺寸强制缩放

/***
*
* @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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  图片 压缩 java