springboot 图片大小压缩

application.properties配置文件

#后端接收图片大小
spring.servlet.multipart.max-file-size=50MB
spring.servlet.multipart.max-request-size=50MB

java工具类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
/
/**
     * 请求调用方法
     * gb
     *
     * @param fromPath1 byte直接文件图片
     * @return 剪切后的byte文件
     */
    public static byte[] imageSet(byte[] fromPath1) throws Exception {
        return imageChangeSize(fromPath1, 470, 635);
    }

    /**
     * @param data   byte类型图片
     * @param max_wi 图片修改后最大的宽
     * @param max_he 图片修改后最大的高
     * @return
     * @throws Exception
     * @Description 更改图片内容的大小 byte【】 类型
     */
    public static byte[] imageChangeSize(byte[] data, int max_wi, int max_he) throws Exception {
        ImageIO io = null;
        float rate = 1;
        /*图片的原始宽 120*/
        int oldwi;
        /*图片的原始高 120*/
        int oldhe;
        /*图片修改后的宽 0*/
        int new_wi = 0;
        /*图片修改后的高 0*/
        int new_he = 0;
        /*拿到byte图片*/
        InputStream is = new ByteArrayInputStream(data);
        BufferedImage bufImg = ImageIO.read(is);
        /*图片的原始宽度*/
        oldwi = bufImg.getWidth();
        /*图片的原始高度*/
        oldhe = bufImg.getHeight();
        //
        rate = (float) oldwi / (float) oldhe;
        /*如果图片的原宽大于最大宽度,并且原高小于等于最大高度。则证明图片过宽了,将图片宽度设置为最大宽度,此时需要等比例减小高度*/
        if (oldwi > max_wi && oldhe <= max_he) {
            new_wi = max_wi;
            new_he = new Float((float) new_wi / rate).intValue();
            /*如果图片的原宽和原高都大于或者都小于其所对应的最大值,则以任意一方为主(此处以最大高度为主)*/
        } else if (oldwi >= max_wi && oldhe >= max_he || oldwi <= max_wi && oldhe <= max_he) {
            new_he = max_he;
            new_wi = new Float(new_he * rate).intValue();
            /*如果图片的原宽小于于最大宽度,并且原高大于等于最大高度。则证明图片过高了,将图片宽度设置为最大高度,此时需要等比例减小宽度*/
        } else if (oldwi <= max_wi && oldhe > max_he) {
            new_he = max_he;
            new_wi = new Float(new_he * rate).intValue();
        }
//        System.err.println("原宽度:" + oldwi + "原高度:" + oldhe + "_" + rate);
        /*开始改变大小*/
        ImageObserver ser = null;
        BufferedImage bf = new BufferedImage(new_wi, new_he, BufferedImage.TYPE_INT_RGB);
        bf.getGraphics().drawImage(bufImg, 0, 0, new_wi, new_he, null);
//        System.err.println("新宽度:" + bf.getWidth() + "-" + "新高度:" + bf.getHeight());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        //转换编码格式JPEG
        ImageIO.write(bf, "jpeg", out);
        byte[] re = out.toByteArray();
        //logger.info("【图片剪切】| 图片原大小={}kb | 压缩后大小={}kb", (data.length / 1024), (re.length / 1024));
        return re;
    }

使用

controller

	@RequestMapping(value = "/getImage", method = RequestMethod.POST)
    @ResponseBody
    public JsonData getidcart(@RequestParam(value = "front", required = false) MultipartFile front) throws Exception {
        byte[] IdCartFront;
        /**
         *  图片字节
         *  判断压缩 >300kb就压缩到300kb以下 300000k=300kb 设置宽高px--->转小kb
         */
        if (front.getSize() > SIZE_DEFUALT) {
            IdCartFront = ImageUtils.imageSet(front.getBytes());
        } else {
            IdCartFront = front.getBytes();
        }

页面

<!--身份证正面-->
            <div class="photo" id="photo" enctype="multipart/form-data">
                <input type="file" multiple="multiple" accept="image/*"
                       onchange="getImg(event,'photo',1)" enctype="multipart/form-data" id="face" required/>
            </div>

js

/** 获取照片 */
function getImg(e, eId, next) {
    var imgFile = e.target.files[0];
    var newImgFile = window.webkitURL.createObjectURL(imgFile);
    document.getElementById("" + eId + "").style.backgroundImage = "url(" + newImgFile + ")";

    if (next == 1) {
        front = imgFile;
    } else if (next == 2) {
        back = imgFile;
    } else if (next == 3) {
        face = imgFile;
    }
}
//ajax:
************************
//将file文件转为formdata,Ajax传到后台
    formData = new FormData();
    formData.append('front', front);
  
   			url: url,
            type: 'POST',
            cache: false,
            data: formData,
            processData: false,
            contentType: false,
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringBoot中,可以使用Thumbnails库对图片进行压缩。根据引用内容和的规则,当设定缩放的图片宽和高时,原来图片的宽和高比例会保持不变。如果设定的宽比原来的大,高比原来的小,最后缩完高会缩小到设定的高;如果设定的宽比原来的小,高比原来的大,最后缩完宽会缩小到设定的宽。 示例代码如下: ``` @Test void contextLoads() { try { Thumbnails.of("C:\\Users\\Administrator\\Desktop\\指定大小\\6.jpg") .size(1500, 400) .toFile("C:\\Users\\Administrator\\Desktop\\指定大小\\6-6.jpg"); } catch (IOException e) { System.out.println("e" + e); e.printStackTrace(); } } ``` 这段代码将指定的图片路径进行压缩,将宽度设定为1500像素,高度设定为400像素,然后保存为新的文件。同样,根据引用的规则,可以将宽度设定为400像素,高度设定为1500像素进行压缩。 你可以根据需要修改代码中的图片路径和设定的宽高值,然后运行该方法即可实现图片的压缩。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [springboot 整合thumbnailator- 图片压缩](https://blog.csdn.net/qq_42778001/article/details/121014322)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值