图片压缩上传(Springboot mybatis-plus)

@PostMapping("/saveAndSubmitBill")
    public HttpResult saveAndSubmitBill(HttpServletRequest request, @RequestParam("file") MultipartFile[] images,
                                        @RequestParam("deptId") Long deptId) throws Exception {



        for (MultipartFile multipartFile : images) {
            String fileType = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().indexOf("."));
            if (!".png".equals(fileType) && !".jpg".equals(fileType) && !".gif".equals(fileType) && !".jpeg".equals(fileType)) {
                return "图片格式不正确";
            }
        }

        List<ChkBillImg> chkBillImgList = new ArrayList<>();
            for (MultipartFile multipartFile : images) {
                //压缩图片
                String filePath = getNewImgFilePath("D:\\file", "billImg",  multipartFile);
                filePath = ImageUtil.imgCompress(filePath, multipartFile);
                ChkBillImg chkBillImg = new ChkBillImg();
                chkBillImg.setUrl(filePath);
                chkBillImgList.add(chkBillImg);
            }
        chkBillImgService.saveBatch(chkBillImgList);

        return HttpResult.ok();
    }

    public static String getNewImgFilePath(String rootPath,String imgServicePath,MultipartFile multipartFile){
        String fileType = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().indexOf("."));
        //通过用户名获取所在地区行政划分编码
        Date date = new Date();
        DateFormat df = new SimpleDateFormat("yyyy_MM_dd");
        DateFormat dftime = new SimpleDateFormat("HH_mm_ss");
        String day = df.format(date);
        String time = dftime.format(date);
        String imageFolder = rootPath + imgServicePath + File.separator +  day;
        String uuid = String.valueOf(UUID.randomUUID()).replace("-", "");
        String filePath = imageFolder+File.separator +  time + "_" + uuid + fileType;
        return filePath;
    }
package blog;

import cn.edu.qfnu.soft.audit.model.SetImgPath;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.*;
import java.io.File;
import java.io.IOException;

public class ImageUtil {

    /**
     * 图片转为jpg并压缩存储
     * @param filePath 存储路径
     * @param multipartFile 压缩文件
     * @return 存储地址
     * @throws IOException
     */
    public static String imgCompress(String filePath, MultipartFile multipartFile) throws IOException {//String areaId, SetImgPath rootPath,
//        String filePath = FileIOUtil.getNewImgFilePath(rootPath.getImgUrl(),"billImg",areaId,multipartFile);

        //2. MultipartFile 转 File
        File image = new File(filePath);
        FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), image);
        //png图片转jpg
        File outFile = new File(filePath);
        String extName = FileUtil.extName(filePath);
        if ("png".equals(extName) || "gif".equals(extName)){
            String jpgFilePath = filePath.substring(0,filePath.lastIndexOf("."))+".jpg";
            File jpgImg = new File(jpgFilePath);
            ImgUtil.convert(image,jpgImg);
            image.delete();
            image = jpgImg;
            outFile = jpgImg;
            filePath = jpgFilePath;
        }
        //图片压缩
        ImgUtil.compress(image,outFile,0.4f);
        return filePath;
    }
  
    public static BufferedImage change2jpg(File f) {
        try {
            Image i = Toolkit.getDefaultToolkit().createImage(f.getAbsolutePath());
            PixelGrabber pg = new PixelGrabber(i, 0, 0, -1, -1, true);
            pg.grabPixels();
            int width = pg.getWidth(), height = pg.getHeight();
            final int[] RGB_MASKS = { 0xFF0000, 0xFF00, 0xFF };
            final ColorModel RGB_OPAQUE = new DirectColorModel(32, RGB_MASKS[0], RGB_MASKS[1], RGB_MASKS[2]);
            DataBuffer buffer = new DataBufferInt((int[]) pg.getPixels(), pg.getWidth() * pg.getHeight());
            WritableRaster raster = Raster.createPackedRaster(buffer, width, height, width, RGB_MASKS, null);
            BufferedImage img = new BufferedImage(RGB_OPAQUE, raster, false, null);
            return img;
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }
  
    public static void resizeImage(File srcFile, int width,int height, File destFile) {
        try {
            if(!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            Image i = ImageIO.read(srcFile);
            i = resizeImage(i, width, height);
            ImageIO.write((RenderedImage) i, "jpg", destFile);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
      
    public static Image resizeImage(Image srcImage, int width, int height) {
        try {
  
            BufferedImage buffImg = null;
            buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            buffImg.getGraphics().drawImage(srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
  
            return buffImg;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
  
}
posted @ 2021-05-08 15:47  Ideaway  阅读(712)  评论(0)    收藏  举报