Spring Boot —— 图片上传生态类

来源:互联网 发布:淘宝宝贝分类源代码 编辑:程序博客网 时间:2024/05/16 19:53

写在前面

在常老师写的spring-mvc图片上传工具类UploadResolver的基础上,重写了这个 上传图片的工具类。增加了几个图片处理的方法(按比例缩放,指定宽高缩放,指定坐标裁剪)。我称之为springboot文件上传生态类。

项目结构为Springboot+mybatis
jdk 1.8
工具 idea
贴出这几个类的大致功能。

文件上传类的结构
spring-boot取消了大多数的配置文件,因此图片上传的一些基础配置数据被放置在了application.properties文件或application.yml文件中。(此处小编选用的是yml文件)相关配置项为:

upload:  uploadPath: D:/image   保存文件的本地路径  thumbDir: thumbs       缩略图、裁剪图等存放的文件夹  imageHeight: 100       默认缩略后的高度  imageFormat: jpg       统一保存格式大家需要什么配置,可自行添加。

UploadResolverProperties.java

/** * @author longping jie * @name UploadResolverProperties * @description the class is 上传文件基本配置项目,从配置文件中读取数据 * @date 2017/9/22 */@ConfigurationProperties("upload")public class UploadResolverProperties {    private String uploadPath;    private String thumbDir;    private Integer imageHeight;    private String imageFormat;    public String getUploadPath() {        return uploadPath;    }    public void setUploadPath(String uploadPath) {        this.uploadPath = uploadPath;    }    public String getThumbDir() {        return thumbDir;    }    public void setThumbDir(String thumbDir) {        this.thumbDir = thumbDir;    }    public Integer getImageHeight() {        return imageHeight;    }    public void setImageHeight(Integer imageHeight) {        this.imageHeight = imageHeight;    }    public String getImageFormat() {        return imageFormat;    }    public void setImageFormat(String imageFormat) {        this.imageFormat = imageFormat;    }}

HandleImageWays.java

/** * @author longping jie * @name HandleImageWays * @description the class is 处理图片的方法类型常量的类 * @date 2017/9/22 */public class HandleImageWays {    //按比例缩放一张图片    public static final String SCALING_IMAGE="SCALING_IMAGE";    //按宽高缩放一张图片    public static final String SCALING_IMAGE_WH="SCALING_IMAGE_WH";    //指定坐标裁剪一张图片    public static final String TRIMIMAGE_POINT="TRIMIMAGE_POINT";}

HandleImageDataModel.java

/** * @author longping jie * @name HandleImage * @description the class is 裁剪图片的数据模型类 * 图片缩放等配置数据项 * @date 2017/9/21 */public class HandleImageDataModel {    //图片当前显示在画布上的的高度    private int presentHeight;    //图片当前显示在画布上的的宽度    private int presentWidth;    //裁剪的x坐标    private int x;    //裁剪的y坐标    private int y;    //裁剪的高度    private int h;    //裁剪的宽度    private int w;    //裁剪后需要的宽度    private int need_w;    //裁剪后需要的高度    private int need_h;    //需要缩放的比例    private double scaling;    //需要缩放的宽度    private int scaling_w;    //需要缩放的高度    private int scaling_h;    public int getPresentHeight() {        return presentHeight;    }    public void setPresentHeight(int presentHeight) {        this.presentHeight = presentHeight;    }    public int getPresentWidth() {        return presentWidth;    }    public void setPresentWidth(int presentWidth) {        this.presentWidth = presentWidth;    }    public int getX() {        return x;    }    public void setX(int x) {        this.x = x;    }    public int getY() {        return y;    }    public void setY(int y) {        this.y = y;    }    public int getH() {        return h;    }    public void setH(int h) {        this.h = h;    }    public int getW() {        return w;    }    public void setW(int w) {        this.w = w;    }    public int getNeed_w() {        return need_w;    }    public void setNeed_w(int need_w) {        this.need_w = need_w;    }    public int getNeed_h() {        return need_h;    }    public void setNeed_h(int need_h) {        this.need_h = need_h;    }    public double getScaling() {        return scaling;    }    public void setScaling(double scaling) {        this.scaling = scaling;    }    public int getScaling_w() {        return scaling_w;    }    public void setScaling_w(int scaling_w) {        this.scaling_w = scaling_w;    }    public int getScaling_h() {        return scaling_h;    }    public void setScaling_h(int scaling_h) {        this.scaling_h = scaling_h;    }}

UploadResolver.java

/** * @author longping jie * @name UploadResolver * @description the class is 上传图片的工具类,封装有图片缩放和剪裁 * @date 2017/9/22 */public class UploadResolver {    @Autowired    UploadResolverProperties uploadResolverProperties;    String dateName;    public UploadResolver() {        LocalDate dt = LocalDate.now();        int year = dt.getYear();        int month = dt.getMonthValue();        int date = dt.getDayOfMonth();        String monthStr = month + "";        String dateStr = date + "";        if (month < 10) {            monthStr = "0" + monthStr;        }        if (date < 10) {            dateStr = "0" + date;        }        dateName = String.format("%s-%s-%s", year, monthStr, dateStr);    }    /**     * 图片上传的类     *     * @param image      需要上传的图片文件对象     * @param fileName  指定一个名字     * @param handleImageWays      处理图片的方式,如缩放,裁剪等     * @param dataModel 处理图片的数据模型     * @throws IOException     */    public void saveImage(MultipartFile image, String fileName, String handleImageWays, HandleImageDataModel dataModel) throws IOException {        String imageName = String.format("%s/%s/%s.jpg", uploadResolverProperties.getUploadPath(),                dateName, fileName);        String thumbName = String.format("%s/%s/%s/%s.jpg", uploadResolverProperties.getUploadPath(),                dateName, uploadResolverProperties.getThumbDir(), fileName);        File imageFile = new File(imageName);        File thumbFile = new File(thumbName);        if (!imageFile.getParentFile().exists()) {            imageFile.getParentFile().mkdirs();            thumbFile.getParentFile().mkdirs();        }        image.transferTo(imageFile);        switch (handleImageWays){            case HandleImageWays.SCALING_IMAGE:                changeSize_Scaling(imageFile,thumbFile,dataModel);                break;            case HandleImageWays.SCALING_IMAGE_WH:                changeSize_WH(imageFile,thumbFile,dataModel);                break;            case HandleImageWays.TRIMIMAGE_POINT:                trimImage(imageFile,thumbFile,dataModel);                break;        }    }    /**     * 指定宽度高度缩放图片     *     * @param file    原图片文件     * @param newFile 目标图片文件     */    private void changeSize_WH(File file, File newFile,HandleImageDataModel dataModel) throws IOException {        //变为400*300,遵循原图比例缩或放到400*某个高度        Thumbnails.of(file).size(dataModel.getScaling_w(), dataModel.getScaling_h()).toFile(newFile);    }    /**     * 指定比例缩放图片     *     * @param file     * @param newFile     * @throws IOException     */    private void changeSize_Scaling(File file, File newFile, HandleImageDataModel dataModel) throws IOException {        Thumbnails.of(file).scale(dataModel.getScaling()).toFile(newFile);//按比例缩小    }    /**     * 判断一个文件是否是图片类型     *     * @param type 文件类型     * @return 是否是图片类型     */    public boolean checkImageFileType(String type) {        String[] types = {".PNG", ".JPG", ".JPEG", ".BMP", ".GIF"};        boolean res = false;        for (String t : types) {            if (t.equals(type.toUpperCase())) {                res = true;                break;            }        }        return res;    }    /**     * 用uuid重命名文件     *     * @param fileName 文件原名     * @return 文件新的名字     */    private String createFileName(String fileName) {        return UUID.randomUUID().toString().replaceAll("-", "") + "." +                fileName.substring(fileName.lastIndexOf(".") + 1);    }    /**     * 裁剪图片     *     * @param file      原图片文件     * @param newFile   新图片文件     * @param dataModel 裁剪需要的数据模型     */    private void trimImage(File file, File newFile, HandleImageDataModel dataModel) throws IOException {        BufferedImage buf = Thumbnails.of(file).width(dataModel.getPresentWidth()).height(dataModel.getPresentHeight())                .asBufferedImage();        Thumbnails.of(buf).sourceRegion(dataModel.getX(), dataModel.getY(), dataModel.getW(), dataModel.getH())                .size(dataModel.getNeed_w(), dataModel.getNeed_h()).toFile(newFile);    }    @Override    public String toString() {        return "UploadResolver{" +                "uploadResolverProperties=" + uploadResolverProperties +                ", dateName='" + dateName + '\'' +                '}';    }

UploadResolverConfig.java

/** * @author longping jie * @name UploadResolverConfig * @description the class is 装载UploadResolver对象 * @date 2017/9/22 */@Configuration@EnableConfigurationProperties(UploadResolverProperties.class)public class UploadResolverConfig  {    @Bean    public UploadResolver getUploadResolver(){        return  new UploadResolver();    }}

使用时

@Autowired    UploadResolverConfig uploadResolverConfig;    @Test    public void findOne() {        //直接调用UploadResolver中的方法,并指定处理图片的方式和响应的数据模型。        System.out.println(uploadResolverConfig.getUploadResolver());    }

相关类还没有在前端页面中进行具体调试,贴出来仅供大家参考,同时,代码有需要优化的地方,和潜在的bug,还希望各位读者,积极在下方评论区提出。以便作者更好地完善这个功能模块。