栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

html上传图片base64码,Springboot java 接收并压缩保存

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

html上传图片base64码,Springboot java 接收并压缩保存

1.导入thumbnailator依赖(用于图片压缩)

pom.xml



    net.coobird
    thumbnailator
    0.4.14

2.java controller类中接口,接收前端base64码并保存成图片

@RequestMapping("/upload/base64/")
public void uploadbase64(HttpServletRequest req, HttpServletResponse response) {
    //获取前端传来的base64码  去掉base64码的data:image/png;base64,
    String base64String = req.getParameter("photo").replaceAll("data:image/png;base64,", "");
    base64Decoder decoder = new base64Decoder();
    try {
        // base64解码
        byte[] bytes = decoder.decodeBuffer(base64String);
        for (int i = 0; i < bytes.length; ++i) {
            // 调整异常数据
            if (bytes[i] < 0) {
                bytes[i] += 256;
            }
        }
        // 生成jpg图片
        String uploadfilePath =  "XXX.jpg";
        String uploadfilePath_compress =  "XXX_compress.jpg";
        // 生成文件jpg
        File imageFile = new File(uploadfilePath);
        imageFile.createNewFile();
        if (!imageFile.exists()) {
            imageFile.createNewFile();
        }
        OutputStream imageStream = new FileOutputStream(uploadfilePath);
        imageStream.write(bytes);
        imageStream.flush();
        imageStream.close();
        boolean compressFlag = MyPicUtil.compressQualityAndSize(uploadfilePath,uploadfilePath_compress, 1f, 0.1f);
        if (compressFlag == false) {
            return;
        }
        File oldFile = new File(uploadfilePath);
        // 原图片删除
        oldFile.delete();
    } catch (Exception e) {
        log.info("上传错误");
        log.error(e.toString(), e);
    }
}

3.MyPicUtil.java 图片压缩工具类

@Slf4j
public class MyPicUtil {

    
    public static boolean compressQualityAndSize(String fromfilePath, String tofilePath, Float sizeRatio, Float qualityRatio) {
        try {
            Thumbnails.of(new File(fromfilePath))
                    .scale(sizeRatio) //图片大小(长宽)压缩 从0按照
                    .outputQuality(qualityRatio) //图片质量压缩比例 从0-1,越接近1质量越好
                    .toOutputStream(new FileOutputStream(tofilePath));
            return true;
        } catch (IOException e) {
            log.warn(e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
    
}

4.前端测试页面




    
    
    Insert title here



    上传照片测试
    
    
     



5.Springboot请求默认上限2mb,可以在yml配置中修改

application.yml

server:
#默认8KB
  max-http-header-size: 16KB
  tomcat:
    #默认2MB
    max-http-form-post-size: 4MB

小结:我可以顺利运行,但是前端上传图片转base64码感觉还是有些问题,有时候图片200k转成base64码就变1M多了,而且java压缩的代码有概率压缩后比原来还大,可以加个判断

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/631131.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号