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

JAVA 图片压缩和图片转base64

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

JAVA 图片压缩和图片转base64

使用第三方jar


            net.coobird
            thumbnailator
            0.4.15
        
        
            com.twelvemonkeys.imageio
            imageio-jpeg
            3.6
        

代码

    public static String getFileBase64StrByFilePath(String filePath){
        if(StringUtils.isBlank(filePath)){
            return null;
        }

        InputStream in = null;
        String base64 = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(filePath);
            byte[] data = new byte[in.available()];
            in.read(data);
            in.close();
            base64 = getFileBase64StrByBytes(data);
        } catch (Throwable t) {
            t.printStackTrace();
        }finally {
            IoUtil.close(in);
        }
        return base64;
    }

    
    public static String getFileBase64StrByBytes(byte[] data){
        if(data == null){
            return null;
        }
        String base64 = null;
        //读取图片字节数组
        try {
            BASE64Encoder encoder = new BASE64Encoder();
            base64 = encoder.encode(data);
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return base64;
    }

    
    public static byte[] compressImage(String path, int fileMin) {
        byte[] smallImage = null;
        try {
            long desFileSize = 1024;
            File imgFile = new File(path);
            long fileSize = imgFile.length();

            //判断大小,如果小于指定大小,不压缩,如果大于等于指定大小,压缩
            if(fileSize > (desFileSize * fileMin)){
                Double accuracy = 0.8;
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                //计算宽高
                BufferedImage bim = ImageIO.read(imgFile);
                int imgWidth = bim.getWidth();
                int imgHeight = bim.getHeight();
                int desWidth = NumberUtil.multiply(new BigDecimal(imgWidth), new BigDecimal(accuracy)).intValue();
                int desHeight = NumberUtil.multiply(new BigDecimal(imgHeight), new BigDecimal(accuracy)).intValue();
                Thumbnails.of(path).size(desWidth, desHeight).outputQuality(accuracy).toOutputStream(out);
                smallImage = out.toByteArray();
            }else{
                FileInputStream in = new FileInputStream(imgFile);
                smallImage = new byte[in.available()];
                in.read(smallImage);
                IoUtil.close(in);
            }
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return smallImage;
    }

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

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

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