图片压缩工具类

java图片压缩工具类

@Slf4j
public class ImageUtil {

    /**
     * 图片压缩
     * @param oldImg
     * @return
     */
    public static byte[] reduceImg(InputStream oldImg) {
        InputStream is = null;
        ByteArrayOutputStream os = null;
        try {
            Image src = ImageIO.read(oldImg);
            //获取图片原分辨率
            int oldWidthdist = src.getWidth(null);
            int oldHeightdist = src.getHeight(null);
            //计算图片高宽比例数值
            Double proportion =  Double.valueOf(oldHeightdist)/Double.valueOf(oldWidthdist);
            //固定宽度为500 高度根据比例值进行计算
            int widthdist = 500;
            int heightdist = Double.valueOf(500*proportion).intValue();
            
            BufferedImage tag= new BufferedImage(widthdist, heightdist, BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);
            os = new ByteArrayOutputStream();
            ImageIO.write(tag, "jpeg", os);
            return os.toByteArray();
        } catch (IOException e) {
            log.error("图片压缩失败--{}",e);
        }finally {
            if (os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 重复压缩 
     * 目标大小  < 102400byte
     * 最大重复压缩次数  5
     * @param oldImg
     * @return
     */
    public static byte[] reduceImgWhile(InputStream oldImg) {
        byte[] bytes = null;
        int i = 0;
        do {
            if (i>0){
                oldImg = new ByteArrayInputStream(bytes);
            }
            i++;
            log.info("压缩"+i+"次");
            bytes = reduceImg(oldImg);
        }while (bytes.length > 102400 && i < 5);
        return bytes;
    }

    /**
     * 对url外链进行重复目标压缩
     * @param url
     * @return
     */
    public static byte[] reduceImgUrl(String url){
        try {
            log.info("压缩图片链接:{}",url);
            URL imgUrl = new URL(url);
            InputStream inputStream = imgUrl.openConnection().getInputStream();
            return reduceImgWhile(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容