java对base64的图片进行压缩

目标:用java将图片的base64码压缩到40kb以下。

依赖

  <!--  压缩图片-->
        <dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.8</version>
        </dependency>

压缩的方法:

 

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.apache.commons.codec.binary.Base64;
import java.io.*;

/*
   图片压缩
 */

@Service
public class Imageys {

    /**
     * 压缩base64编码至40K以内
     * @param base64Img
     * @return
     */
    public   String resizeImageTo40K(String base64Img) {
        try{
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes1 = decoder.decodeBuffer(base64Img);
            InputStream stream = new ByteArrayInputStream(bytes1);
            BufferedImage src = ImageIO.read(stream);
            //BufferedImage output = Thumbnails.of(src).size(src.getWidth() / 3, src.getHeight() / 3).asBufferedImage();
            BufferedImage output = Thumbnails.of(src).size(50, 50).asBufferedImage();
            String base64 = imageToBase64(output);
            if (base64.length() - base64.length() / 8 * 2 > 40000) {
                output = Thumbnails.of(output).scale(1 / (base64.length() / 40000)).asBufferedImage();
                base64 = imageToBase64(output);
            }
            return base64;
        } catch (Exception e) {
            return base64Img;
        }
    }

    // BufferedImage转换成base64,在这里需要设置图片格式,如下是jpg格式图片:
    public static String imageToBase64(BufferedImage bufferedImage) {
        Base64 encoder = new Base64();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage, "jpg", baos);
        } catch (IOException e) {
        }
        return new String(encoder.encode((baos.toByteArray())));
    }

}

 

 

 

调用方法和输出结果

 //压缩图片
@Autowired
Imageys imageys;
String imageBase64 = "/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDA.........";//此处省略
System.out.println("old:"+imageBase64.length());
imageBase64 = imageys.resizeImageTo40K(imageBase64);
System.out.println("new:"+imageBase64.length());

//输出结果
old:328724
new:7974

 

资源丰富的的网盘资源:网盘资源大全! 推荐一个适合零基础学习SQL的网站:不用安装数据库,在线轻松学习SQL!
posted @ 2022-09-08 13:59  万笑佛  阅读(3528)  评论(0编辑  收藏  举报