springBoot图片上传对图片高进行百分比剪切

前言:
百分比截取图片高度,在网上找了不少解决方案,也没找到可以直接使用的,最后不断的尝试寻找整合得出一下结果,不知道是我搜索的原因还是这个场景不常见,没找到完全适配的解决方案,经过不断的尝试得以解决,就想着写这篇博文,希望能帮助到大家。

过程:
最开始整了一个小的demo,实现了图片剪切功能,但是没能集成到项目中,在集成到项目中的时候遇到了不少问题,图片上传是通过 MultipartFile 来上传的,MultipartFile上传到服务器好像是一个临时文件,网上找到的解决方案只找到了File具体文件的处理方式,可能对文件流的操作还是太少了不只怎么转换,最后通过将MultipartFile临时文件先存储到本地再通过File读取再进行操作感觉是饶了一大圈,好在最后实现了该功能。

首先这个功能可拆分为4部分:
1、首先获取上传图片的宽和高,也是为了方便后面做图片的剪切。
2、将图片暂存到本地,然后方便对图片进行剪切操作。
3、剪切本地图片然后将本地原始图片替换成剪切的图片。
4、最终返回File

最终代码:


import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Iterator;

/**
 * @Description: 图片处理工具类
 * @Author: huaShangJin
 * @CreateDate: 2022/7/21 23:30
 */
@Slf4j
public class ImageUtil {

    /**
     * @description: 剪切图片
     * @param: file 前端传入要上传的图片流
     * heightPercentage 百分比 高占比
     * savePath 暂存本的图片全路径
     * @return: java.io.File
     * @author HuaShangJin
     * @date: 2022/7/22 14:07
     */
    public static File cutOutImage(MultipartFile multipartFile, Double heightPercentage,String savePath) {
        // 获取图片类型
        String imageType = multipartFile.getOriginalFilename().split("\\.")[1];
        // 1、通过 MultipartFile 获取宽高
        // 图片原始宽度
        int width = 0;
        // 图片原始高度
        int height = 0;
        try {
            // 获取原始图片的InputStream 流
            InputStream originalInput = multipartFile.getInputStream();
            BufferedImage bufferedImage = ImageIO.read(originalInput);
            if (bufferedImage == null) {
                // 证明上传的文件不是图片,获取图片流失败,不进行下面的操作
                throw new BusinessException("请上传正确图片格式 !");
            }
            width = bufferedImage.getWidth();
            height = bufferedImage.getHeight();
        } catch (IOException e) {
            e.printStackTrace();
            log.info("获取上传原始图片高宽失败:" + e.getMessage());
        }

        // 2、将图片文件写入本地
        // 创建要创建 文件的file对象
        File saveUrlFile = new File(savePath);
        // 检测该路径是否存在父文件夹目录  有则返回true无则进行创建
        if (!saveUrlFile.getParentFile().exists()) {
            saveUrlFile.getParentFile().mkdirs();
        }
        try {
            // 将图片文件保存本地指定动态获取的路径
            multipartFile.transferTo(saveUrlFile);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 3、读取本地图片文件最终将文件替换成截取完毕的图片
        // 创建文件输入流
        InputStream inputFile = null;
        // 创建图片读取流
        ImageInputStream imageStream = null;
        try {
            // 从文件流中读取数据
            inputFile = new FileInputStream(saveUrlFile);
            // 将图片转化为 imageReader
            Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageType);
            ImageReader reader = readers.next();
            // 读入图片
            imageStream = ImageIO.createImageInputStream(inputFile);
            reader.setInput(imageStream, true);
            // 参数用来装 图片需要设置的 高宽
            ImageReadParam param = reader.getDefaultReadParam();
            // 图片裁剪范围 当前业务只需要截取 图片最底下的一部分即可 所以对高进行处理
            Rectangle rect = new Rectangle(width, (int) (height * heightPercentage));
            param.setSourceRegion(rect);
            // 将裁剪出图片 输出到指定文件夹
            ImageIO.write(reader.read(0, param), imageType, new File(savePath));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭使用完毕的流,防止资源占用
            try {
                inputFile.close();
                // 断言判断图片流文件不为空
                assert imageStream != null;
                imageStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 4、返回file
        return saveUrlFile;
    }
}

调用该方法:

 // multipartfile前端传入的图片流, 0.89 高度剪切百分比, SpringBeanUtil.getProperty("upload.path")文件暂存地址+ 上传图片名称
 File LocalFile = cutOutImage(multipartfile, 0.89, 
 SpringBeanUtil.getProperty("upload.path") + multipartfile.getOriginalFilename());

完毕~

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值