springboot图片压缩后上传 MultipartFile转为File文件流 按照指定宽高压缩上传

开发中,后台接口常用MultipartFile类型接收前端上传的文件流,但常需转为File类型以读取文件属性进行压缩上传。本文分享具体实现过程,包括封装动态生成文件目录的工具类,以及按指定宽高压缩并上传图片的代码实现。

 

在开发中,前端上传的文件流,在后台接口中通常是用MultipartFile类型的流格式接收,但是接收到的文件流往往不能满足我们的使用要求,我们需要转为File类型的文件流再去读取文件的宽高,大小等属性进行压缩上传等操作。本工具类为大家分享具体实现过程。接口规范:接收前端传的文件流,以及指定的目标压缩宽高,和压缩完需要上传到的指定目录。

首先封装一个动态生成文件目录的文件路径工具类

 
  1. package com.demo.serverProvider.utils;

  2.  
  3. import java.io.File;

  4. import java.text.SimpleDateFormat;

  5. import java.util.Date;

  6. import org.apache.commons.lang.StringUtils;

  7.  
  8. /**

  9. * 创建时间:2019年2月15日 上午10:05:00

  10. * 项目名称:server-provider

  11. * 类说明:文件上传路径生成

  12. * @author guobinhui

  13. * @since JDK 1.8.0_51

  14. */

  15. public class UploadPathUtils {

  16. /**

  17. * 图片最终生成的目录结构:host(服务器域名或主机IP)+文件根目录(虚拟目录)+商品图片目录+日期目录+图片名称(含后缀)

  18. * 图片最终存储结构示例:http://10.220.146.3/uploadBaseDir/productPic/20190215/abc.jpg

  19. * 注意:上传业务处理时需要根据服务器系统是windows还是linux配置物理路径和虚拟路径的映射

  20. */

  21.  
  22. private final static SimpleDateFormat YYYY = new SimpleDateFormat("yyyy");

  23. private final static SimpleDateFormat MM = new SimpleDateFormat("MM");

  24. private final static SimpleDateFormat DD = new SimpleDateFormat("dd");

  25.  
  26. private static String getYear(Date date) {

  27. if (null == date) {

  28. date = new Date();

  29. }

  30. return YYYY.format(date);

  31. }

  32.  
  33. private static String getMM(Date date) {

  34. if (null == date) {

  35. date = new Date();

  36. }

  37. return MM.format(date);

  38. }

  39.  
  40. private static String getDD(Date date) {

  41. if (null == date) {

  42. date = new Date();

  43. }

  44. return DD.format(date);

  45. }

  46. /*按照日期格式动态生成日期目录*/

  47. private static String getDateDir() {

  48. Date date = new Date();

  49. StringBuilder path = new StringBuilder("/");

  50. path.append(getYear(date));

  51. path.append(getMM(date));

  52. path.append(getDD(date));

  53. return path.toString();

  54. }

  55. /*动态生成图片上传完整目录(物理路径)*/

  56. public static String getPicUploadDir(int width,int height){

  57. StringBuilder host = new StringBuilder(ImageConstants.WIN_IMAGE_ROOT_DIR);

  58. host.append(ImageConstants.PRODUCT_PIC_DIR);

  59. host.append(getDateDir());

  60. String fullDir = generatorDir(host);

  61. return fullDir;

  62. }

  63. /*动态生成目录*/

  64. private static String generatorDir(StringBuilder dir){

  65. String fileDir = dir.toString();

  66. if (!StringUtils.isEmpty(fileDir)) {

  67. File file = new File(fileDir);

  68. if (!file.isDirectory() && !file.exists()) {

  69. file.mkdirs();

  70. }

  71. }

  72. return fileDir;

  73. }

  74. }

下面代码是具体的图片按照指定宽高压缩并上传的具体实现过程的封装 

 
  1. /**

  2. * 压缩图片按照指定的宽高压缩原图

  3. * @param img

  4. * @param width

  5. * @param height

  6. * @param outputDir

  7. */

  8. public static void thumbnail(MultipartFile file,int destWidth,int destHeight,String outputDir){

  9. System.out.println("图片压缩开始");

  10. long startTime = System.currentTimeMillis();

  11. //得到上传时的原文件名

  12. String originalFilename = file.getOriginalFilename();

  13. //获取文件后缀名

  14. String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));

  15. //获取文件格式

  16. String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

  17. //获取uuid作为文件名

  18. String name = UUID.randomUUID().toString().replaceAll("-", "");

  19. String saveName = name + suffixName;

  20. //存储目录

  21. String picDir = UploadPathUtils.getPicUploadDir(destWidth,destHeight);

  22. //图片存储全路径

  23. String outputPath = picDir + '/' + saveName;

  24. OutputStream fos = null;

  25. try {

  26. //读取源图

  27. BufferedImage BI = ImageIO.read(file.getInputStream());

  28. double srcWidth = BI.getWidth(); // 源图宽度

  29. double srcHeight = BI.getHeight(); // 源图高度

  30. if ((int)srcWidth >= destWidth && (int)srcHeight >= destHeight) {

  31.  
  32. fos = new FileOutputStream(outputPath);

  33. Image image = BI.getScaledInstance(destWidth, destHeight, Image.SCALE_SMOOTH);

  34.  
  35. BufferedImage tag = new BufferedImage(destWidth, destHeight,BufferedImage.TYPE_INT_RGB);

  36. Graphics g = tag.getGraphics();

  37. g.setColor(Color.RED);

  38. g.drawImage(image, 0, 0, null); //绘制处理后的图

  39. g.dispose();

  40. ImageIO.write(tag,ext,fos);

  41. System.out.println("图片压缩并存储结束");

  42. long endTime = System.currentTimeMillis();

  43. System.out.println("图片压缩共计耗时:" +(endTime-startTime)+"毫秒" );

  44. }

  45. } catch (FileNotFoundException e) {

  46. // TODO Auto-generated catch block

  47. e.printStackTrace();

  48. } catch (IOException e) {

  49. // TODO Auto-generated catch block

  50. e.printStackTrace();

  51. }finally{

  52. if(fos != null){

  53. try {

  54. fos.close();

  55. } catch (IOException e) {

  56. // TODO Auto-generated catch block

  57. e.printStackTrace();

  58. }

  59. }

  60. }

  61. }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值