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; }
相关文章推荐
- SpringMVC上传图片并压缩及剪切demo
- springmvc图片上传后压缩处理
- SpringMVC上传图片并压缩及剪切demo
- springmvc中的js上传图片
- Java图片上传压缩处理
- HTML转PDF,再转图片、影像文件,并压缩及上传到ftp服务器
- 移动端利用H5实现压缩图片上传功能
- Flex多图片压缩上传
- H5图片压缩与上传
- IOS上传图片翻转处理重力并压缩大小
- 上传图片到服务器 对图片进行压缩
- SpringMVC上传图片文件到 腾讯云【2018年最新版】【JavaWeb】
- 原生js 对图片的压缩上传
- 移动端图片上传旋转、压缩问题的方法
- HTML5图片上传图片实时预览,通过DataURL将图片压缩“嵌入”到HTML中,优化图片的加载速度和执行效率。
- 上传压缩后的图片并且保持100k不失真的方法
- 图片压缩后上传 不失真的办法
- 项目分享五:H5图片压缩与上传
- 图片上传:FileReader获取,Canvas压缩图片
- 深入研究HTML5实现图片压缩上传