加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

【Java】【43】上传图片,重新命名并缩放到固定大小

发布时间:2020-12-15 08:23:43 所属栏目:Java 来源:网络整理
导读:前言: 1,我这边的需求是,用户上传图片,需要将图片的名称进行处理,并同时生成100*100,300*300大小的图片上传到服务器 2,当时做这个项目的时候是用的SpringMVC 正文: JS部分在此不做记录 后端: Controller层: @ResponseBody@RequestMapping(value =

前言:

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,100,100,fileFormat);
            String LFile = String.format("%s%s_%s_%s_%s.%s",300,300,fileFormat);

            imgCom.resizeFix(100,MFile,fileFormat); 
            imgCom.resizeFix(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,formatName);  
        } else {  
            resizeByHeight(h,formatName);  
        }  
    }  

    /** 
     * 以宽度为基准,等比例放缩图片 
     * @param w int 新宽度 
     */  
    public void resizeByWidth(int w,String formatName) throws IOException {  
        int h = height * w / width;       
        resize(w,h,formatName);  
    }  

    /** 
     * 以高度为基准,等比例缩放图片 
     * @param h int 新高度 
     */  
    public void resizeByHeight(int h,String formatName) throws IOException {  
        int w = width * h / height;  
        resize(w,formatName);  
    }  

    /** 
     * 强制压缩/放大图片到固定的大小 
     * @param w int 新宽度 
     * @param h int 新高度 
     */  
    public void resize(int w,String formatName) throws IOException {        
        BufferedImage image = new BufferedImage(w,Image.SCALE_SMOOTH); //SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢    
        image.getGraphics().drawImage(img,w,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"></bean>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读