Java-多文件上传(如果图片超过指定大小自动压缩)

之前有个需求:文件上传时,如果是图片,超出指定大小,就自动压缩。为了实现这个功能,借用了 google的 Thumbnails 工具,效果还是蛮好的。
全部代码如下:

private void uploadFile(List files) throws IOException{
        Long imgMaxSize = 1024L * 1024L;
        List imgsType = new ArrayList<>(Arrays.asList("BMP","JPG","PNG"));
        if(CollectionUtils.isNotEmpty(files)){
            for(MultipartFile file : files){
                String fileName = file.getOriginalFilename();
                Long fileSize = file.getSize();
                String fileType = file.getContentType().toUpperCase();
                InputStream inputStream = file.getInputStream();
                //如果上传的是图片,且超过指定大小,自动压缩输入流
                if(imgsType.contains(fileType)&&fileSize>imgMaxSize){
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    //压缩输入流,scale是压缩比例;quality是质量比例,0-1之间,越接近1,质量越高
                    Thumbnails.of(inputStream).scale(0.7f).outputQuality(0.25d).toOutputStream(out);
                    InputStream imgInputStream = new ByteArrayInputStream(out.toByteArray());
                    inputStream = imgInputStream;
                }
                //保存文件到本地服务器
                String dirPath = "/src/img/";
                File dir = new File(dirPath);
                if(!dir.exists()){
                    dir.mkdirs();
                }
                File newFile = new File(dirPath+fileName);
                newFile.createNewFile();
                FileOutputStream outStream = new FileOutputStream(newFile);
                int len;
                byte[] buffer = new byte[1024];
                while ((len = inputStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }
                outStream.close();
            }
        }
    }

 

你可能感兴趣的:(java)