基于BufferedImage的文件压缩工具

工具类


@Data
public class ImgUtils {
    /*像素宽度基数*/
    private final static int W_PIXEL = 1024;
    /*1兆以内*/
    final static Long M = 1 * 1000L;


    /**
     * 网络图片压缩
     *
     * @param netImagePath 网络图片路径
     * @return
     */
    public static InputStream netImageToStream(String netImagePath) {
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            // 创建URL
            URL url = new URL(netImagePath);
            // 创建链接
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream inputStream = conn.getInputStream();
            /*获取流的大小*/
            byteArrayOutputStream = toByteArrayOutputStream(inputStream);
            Integer size = byteArrayOutputStream.size() / 1024;
            /*在规定范围内大小则直接返回*/
            if (size < M) {
                return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            }
            return compressImage(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != byteArrayOutputStream) {
                try {
                    byteArrayOutputStream.flush();
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return null;
    }

    /**
     * 基于文件流压缩
     * @param inputStream
     * @return
     */
    public static InputStream netImageToStream(InputStream inputStream) {
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            /*获取流的大小*/
            byteArrayOutputStream = toByteArrayOutputStream(inputStream);
            Integer size = byteArrayOutputStream.size() / 1024;
            /*在规定范围内大小则直接返回*/
            if (size < M) {
                return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            }
            return compressImage(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != byteArrayOutputStream) {
                try {
                    byteArrayOutputStream.flush();
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    /**
     * 文件压缩
     *
     * @param inputStream 要压缩的文件流
     */
    private static InputStream compressImage(InputStream inputStream) throws IOException {
        if (null == inputStream) {
            return null;
        }
        ByteArrayOutputStream outputStream = null;
        try {
            BufferedImage image = ImageIO.read(inputStream);
            /*当前图片的宽度*/
            int width = image.getWidth();
            /*当前图片高度*/
            int height = image.getHeight();
            /*等比例缩放*/
            int widthD = (width / W_PIXEL);
            width = width / widthD;
            height = height / widthD;
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Image compressedImage = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            // 这边是压缩的模式设置
            bufferedImage.getGraphics().drawImage(compressedImage, 0, 0, null);
            outputStream = new ByteArrayOutputStream();
            //将图片按JPEG压缩,保存到out中
            ImageIO.write(bufferedImage, "jpg", outputStream);
            // 输出图片大小
            long outputSize = outputStream.size();
            return new ByteArrayInputStream(outputStream.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != inputStream) {
                try {
                    // 关闭流
                    inputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return new ByteArrayInputStream(outputStream.toByteArray());
    }


    /**
     * inputStream转换ByteArrayOutputStream
     *
     * @param inputStream
     * @return
     */
    public static ByteArrayOutputStream toByteArrayOutputStream(InputStream inputStream) {
        ByteArrayOutputStream outputStream = null;
        try {
            outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
        } catch (IOException i) {
            i.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return outputStream;
    }

}

调用


    @GetMapping("/img/compress")
    @ApiOperation(httpMethod = "GET", value = "测试图片压缩", notes = "测试图片压缩", produces = MediaType.APPLICATION_JSON_VALUE)
    public void imgCompress(@RequestParam("url") String url, HttpServletResponse response) throws IOException {
    	//网络图片url
        InputStream inputStream = ImgUtils.netImageToStream(url);
        response.getOutputStream().write(ImgUtils.toByteArrayOutputStream(inputStream).toByteArray());
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值