zoukankan      html  css  js  c++  java
  • 【Java】【43】上传图片,重新命名并缩放到固定大小

    前言:

    1,我这边的需求是,用户上传图片,需要将图片的名称进行处理,并同时生成100*100,300*300大小的图片上传到服务器

    2,当时做这个项目的时候是用的SpringMVC

    正文:

    JS部分在此不做记录

    后端:

    Controller层:

    @ResponseBody
    @RequestMapping(value = "uploadImage", method = RequestMethod.POST)
    public String uploadImage(String membId, @RequestParam MultipartFile[] myfiles) throws IOException{ 
      return memberService.uploadImage(membId, myfiles);
    }

    Service层:

    public String uploadImage(String membId, MultipartFile[] myfiles) {
        String path = "C:/img/";  //保存图片的文件夹路径 (最好写到配置文件里,包括下面一些参数是否要写到配置文件里,自己酌情处理)       
        File file = new File(path);
        if (!file.exists()) {  //判断文件夹是否存在 (可以先创建文件夹,免得每次上传都要判断)          
            file.mkdirs(); //mkdirs:会一步到位创建目录文件(即使目录不存在);mkdir:如果找不到上一级的目录,会创建失败
        } 
       
        for( MultipartFile myfile : myfiles) { 
            if (myfile.isEmpty()) {
                this.theService.log("找不到对应文件"); //可记录到日志表或者记录到日志文件,包括下面的代码是否要打日志,自己酌情处理
                continue;
            }
    
            if (myfile.getSize() <= 10*1024) {
                this.theService.log("文件大小不能超过10M");
                continue;
            }
    
            String originalFilename = myfile.getOriginalFilename(); //123.jpg → 123
            String fileFormat = originalFilename.substring(originalFilename.lastIndexOf(".")+1);  //123.jpg → jpg
            UUID uuid = UUID.randomUUID();
            String guid = uuid.toString(); //随机数     
                 
            try {
                String newFileName = String.format("%s_%s.%s", membId, guid, fileFormat); 
                String newFile = path + newFileName; //C:/img/xxMembId_yyGuid.jpg
                FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(file, newFileName)); //下载了原图片 
    
                ImgCompress imgCom = new ImgCompress(newFile); 
                String MFile = String.format("%s%s_%s_%s_%s.%s", path, membId, guid, 100, 100, fileFormat);
                String LFile = String.format("%s%s_%s_%s_%s.%s", path, membId, guid, 300, 300, fileFormat);
    
                imgCom.resizeFix(100, 100, MFile, fileFormat); 
                imgCom.resizeFix(300, 300, LFile, fileFormat);
    
                String imgUrl = domain + "/img/" + newFileName; //返回图片路径,domain为项目的域名,img → "C:/img/",可在tomcat的conf - server.xml中配置,是一种映射关系
                return imgUrl;
            } catch (IOException e) {   
                e.printStackTrace();                    
            }                                
           
        } 
        return "";
    }  

    图片压缩工具类ImgCompress

    package com.bf.health.util;
    
    import java.io.*;  
    import java.awt.*;  
    import java.awt.image.*;  
    import javax.imageio.ImageIO;
    
    public class ImgCompress {  
        private Image img;  
        private int width;  
        private int height;
        
        /** 
         * 构造函数 
         */  
        public  ImgCompress(String fileName) throws IOException {  
            File file = new File(fileName);// 读入文件  
            img = ImageIO.read(file);      // 构造Image对象  
            width = img.getWidth(null);    // 得到源图宽  
            height = img.getHeight(null);  // 得到源图长  
        }
        
        /** 
         * 按照宽度还是高度进行压缩 
         * @param w int 最大宽度 
         * @param h int 最大高度 
         */  
        public void resizeFix(int w, int h, String path, String formatName) throws IOException {  
            w = (width > w) ? w : width;
            h = (height > h) ? h : height;
            if (width / height > w / h) {  
                resizeByWidth(w, path, formatName);  
            } else {  
                resizeByHeight(h, path, formatName);  
            }  
        }  
    
        /** 
         * 以宽度为基准,等比例放缩图片 
         * @param w int 新宽度 
         */  
        public void resizeByWidth(int w, String path, String formatName) throws IOException {  
            int h = height * w / width;       
            resize(w, h, path, formatName);  
        }  
    
        /** 
         * 以高度为基准,等比例缩放图片 
         * @param h int 新高度 
         */  
        public void resizeByHeight(int h, String path, String formatName) throws IOException {  
            int w = width * h / height;  
            resize(w, h, path, formatName);  
        }  
    
        /** 
         * 强制压缩/放大图片到固定的大小 
         * @param w int 新宽度 
         * @param h int 新高度 
         */  
        public void resize(int w, int h, String path, String formatName) throws IOException {        
            BufferedImage image = new BufferedImage(w, h, Image.SCALE_SMOOTH); //SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢    
            image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩小后的图  
            File destFile = new File(path);  
            FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流  
            ImageIO.write(image, formatName, new File(path));
            out.close();  
        }
     
    }  

     spring-mvc-config.xml

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <!--1024*200即200k-->  
        <property name="maxUploadSize" value="204800"/>  
        <!--resolveLazily属性启用是为了推迟文件解析,以便在UploadAction 中捕获文件大小异常-->  
        <property name="resolveLazily" value="true"/>    
    </bean> 

     参考博客:

    Java中图片压缩处理 - java小强 - ITeye博客
    https://cuisuqiang.iteye.com/blog/2045855

  • 相关阅读:
    int a=5,则 ++(a++)的值是?
    C中文件操作说明
    最大子序列和 o(n)
    括号匹配
    DOM、SAX、JDOM、DOM4J四种XML解析方法PK
    java中的trim()
    SAX解析XML
    ConcurrentHashMap完全解析(jdk6/7,8)
    为什么推荐Zookeeper作注册中心
    分布式锁的三种实现方式
  • 原文地址:https://www.cnblogs.com/huashengweilong/p/11346579.html
Copyright © 2011-2022 走看看