Java实现图片压缩一般有两种方式,一种是用Graphics+文件格式转换框架完成,这种比较麻烦,代码量多一些,但是压缩出的图片质量会更好一些,另一种是用Google的一个开源框架thumbnailator完成,这种方式不需要写太多的代码就可以实现快速的图片压缩。

介绍一下我的项目情况,我的这个项目初期没有考虑到图片压缩问题,只是做了图片上传功能,没加图片压缩功能,在项目后期再加功能,在原代码的基础上改会显得比较麻烦,我则直接用代码后拦截器来做图片压缩功能,下面讲讲我的实现思路

因为在Controller和Server层已经实现了图片上传功能,不容易修改,首先创建一个代码后拦截器,前端在需要压缩图片的上传端口Request头中添加和后端约定好的标记头,在Server层,上传图片完成后,将图片的唯一id携带到Response中,如果代码后拦截器发现这个请求的Request头中有我们提前约定好的标记头,则在Response中取出图片的唯一id,然后通过id找到这张图片的存储位置,将这个图片压缩完成后,再向前端返回数据,完成这一次图片上传操作

如果你的项目还没有开始写图片上传功能,我建议是将我在拦截器中做的功能,放到Server层实现

下面贴出我的代码:

Maven依赖

<!--        图片压缩插件-->
        <dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.17</version>
        </dependency>

代码后拦截器

package com.example.chinacable.aop.AfterHandle;

import com.example.chinacable.aop.Jwt.*;
import com.example.chinacable.config.BeanUtils;
import com.example.chinacable.mapper.AllMapper;
import com.example.chinacable.pojo.Enterprise_Upload;
import com.example.chinacable.pojo.Upload;
import com.example.chinacable.server.AuthenticationServer;
import com.example.chinacable.server.PublicPageServer;
import com.example.chinacable.server.PublicPageServerInf;
import com.example.chinacable.util.PIC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;


/**
 * 此拦截器为代码后处理器
 */
@Component
public class AfterHandle implements HandlerInterceptor
{




    //如果前端请求头中有此字符串,则需要做压缩处理
    final static String Key = "YsKey";
    final static String Value = "Gjdfgoikr656ewItfMidf6565dsA";


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {


        System.out.println(request.getContextPath());


        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);

        AllMapper allMapper = BeanUtils.getBean(AllMapper.class);

        Enterprise_Upload enterprise_upload = null;
        Upload upload = null;
        String path = "123";







        String Flag = "123";
        try {
            Flag = (String) request.getHeader(Key);
        }catch (Exception e)
        {
            System.out.println(e);
        }

        //判断通过,则该请求需要压缩
        if(Value.equals(Flag))
        {



            String unique_id = response.getHeader("unique_id");

            try {
                enterprise_upload = allMapper.Get_Enterprise_Upload_Byname(unique_id);
                upload = allMapper.Get_Upload_Byname(unique_id);
            }catch (Exception e)
            {
                e.printStackTrace();
            }

            if(upload!=null)
            {
                path = upload.getFull_path();
            }
            if(enterprise_upload != null)
            {
                path = enterprise_upload.getFull_path();
            }

            //调用压缩算法
            PIC.PIC_Compression(path);

        }

    }







}

压缩算法:

 //图片压缩算法
    public static void PIC_Compression(String full_path)
    {
        try {
            Thumbnails.of(full_path)
                    .size(180,180)
                    .toFile(full_path);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐