文件上传MultipartFile实现图片压缩

MultipartFile上传图片并压缩

背景

之前写过一个图片上传,使用了spring的MultipartFile实现的,比较简单,限制了1M的大小,后来产品需求上传图片需压缩,遂着手开始实现

压缩工具

之前用过google的图片压缩工具thumbnailator,简单好用,决定这次也使用这个,具体使用可自行百度
github地址(https://github.com/coobird/thumbnailator), pom引用

		<!--thumbnailator 压缩工具-->
        <dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.8</version>
        </dependency>

代码

talk is cheap,show me the code,话不多说,直接贴代码

	@PostMapping("/uploadrespic")
    @ApiOperation(value = "上传文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "platform",  paramType = "query", dataType = "string", required = true),
            @ApiImplicitParam(name = "module",  paramType = "query", dataType = "string", required = true),
            @ApiImplicitParam(name = "type", paramType = "query", dataType = "string", required = true)
    })
    public ResponseEnvelope imgUpload(
            @RequestPart("file") MultipartFile file,
            @RequestParam String platform,
            @RequestParam String module,
            @RequestParam String type) {
        LoginUser loginUser = LoginContext.getLoginUser(LoginUser.class);
        if (loginUser == null) {
            return new ResponseEnvelope(false, "请先登录");
        }
        //上传图片压缩start
        //记录原MultipartFile,如果压缩异常就用原来的MultipartFile
        MultipartFile oldMultipartFile = file;
        try {
            String fileName = file.getName();
            String originalFilename = file.getOriginalFilename();
            String contentType = file.getContentType();

            LocalDateTime now = LocalDateTime.now();
            //这里就是生成一个绝对路径,使用了公司的工具类FilePathUtil,几个参数都没什么重要含义,里面引用太多,就不贴出来了,大家测试随便给个路径出来能构建file对象就好了
            String absolutePath = FilePathUtil.absolutePath(storagePath, platform, "temp", type, now, file.getOriginalFilename());
            File tempFile = new File(absolutePath);

            Thumbnails.of(file.getInputStream())
                    .scale(1f)
                    .outputQuality(0.99f)
                    .toFile(tempFile);

            FileInputStream fileInputStream = new FileInputStream(tempFile);
            file = new MockMultipartFile(fileName, originalFilename, contentType, fileInputStream);

            fileInputStream.close();
            boolean success = tempFile.delete();
            log.info(CLASS_LOG_PREFIX + "删除临时file success:{}", success);
        } catch (IOException e) {
            log.error(CLASS_LOG_PREFIX + "压缩图片失败,把MultipartFile赋值为原来的值oldFile,exception:{}", e);
            file = oldMultipartFile;
        }
		//上传图片压缩end
		
        LocalDateTime now = LocalDateTime.now();
        String absolutePath = FilePathUtil.absolutePath(storagePath, platform, module, type, now, file.getOriginalFilename());
        Uploader uploader = UploaderFactory.createUploader(type, file, absolutePath);

        if (file.getSize() > DEFAULT_LIMIT) {
            return new ResponseEnvelope(false, "请上传小于1M的图片");
        }
        String baseName = getBaseName(absolutePath) + FilePathUtil.getExtension(absolutePath).toUpperCase();
        Pattern compile = Pattern.compile(DEFAULT_RESFORMAT);
        Matcher matcher = compile.matcher(baseName);
        if (!matcher.find()) {
            return new ResponseEnvelope(false, "允许上传的图片格式为BMP\\JPG\\JPEG\\GIF\\PNG(格式不区分大小写)");
        }

        uploader.upload();
        FileVO fileVO = uploader.getFileVO();
        String returnPath = "/" + FilePathUtil.relativePath(storagePath, absolutePath);
        fileVO.setUrl(returnPath);
        //保存到数据库 并设置返回id
        Long picId = supplyDemandPicService.saveResPic(fileVO, type, absolutePath, loginUser, storagePath);
        fileVO.setResId(picId);
        if (picId == null || picId == 0) {
            return new ResponseEnvelope(false, "Failed to upload picture");
        }
        return new ResponseEnvelope(true, "Success to upload picture", fileVO);
    }

逻辑就在上传图片start和end中间的部分,没什么说的,就是把MultipartFile的输入流压缩到一个临时的file里,然后再根据临时file和之前的参数生成一个新的MultipartFile,完美的在之前的逻辑中嵌入了图片压缩,亲测有效,记录一下

后记

路还很长,不懂得还很多,坚持每天进步!!!

MultipartFile是Spring框架中用于处理文件上传的接口,它可以用于接收前端传递的文件数据。而压缩图片是指将图片文件的大小进行压缩,以减小文件的体积,提高加载速度和节省存储空间。 要实现MultipartFile压缩图片,可以按照以下步骤进行操作: 1. 首先,需要引入相关的依赖。在Spring Boot项目中,可以在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>net.coobird</groupId> <artifactId>thumbnailator</artifactId> <version>0.4.14</version> </dependency> ``` 这个依赖是用于进行图片处理的工具库。 2. 在处理文件上传的Controller方法中,可以通过MultipartFile接收前端传递的文件数据。例如: ```java @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { // 处理文件上传逻辑 // ... } ``` 3. 接下来,可以使用Thumbnailator库对图片进行压缩。首先,需要将MultipartFile转换为File对象: ```java File imageFile = new File(file.getOriginalFilename()); file.transferTo(imageFile); ``` 4. 然后,使用Thumbnailator库对图片进行压缩。例如,可以设置压缩后的图片尺寸为200x200像素: ```java Thumbnails.of(imageFile) .size(200, 200) .toFile(imageFile); ``` 5. 最后,可以将压缩后的图片再次转换为MultipartFile对象,以便后续处理或保存: ```java MultipartFile compressedFile = new MockMultipartFile( imageFile.getName(), new FileInputStream(imageFile) ); ``` 这样,就完成了MultipartFile压缩图片的过程。
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值