java获取网络图片,压缩并转化为base64格式

使用google,Thumbnails工具压缩图片,需要倒入pom包,如下:

<dependency>
			<groupId>net.coobird</groupId>
			<artifactId>thumbnailator</artifactId>
			<version>0.4.8</version>
		</dependency>

处理工具类:

public class ImageBase64Util {

    private static String ImageFormat = "jpg";


    /**
     * 按照比例和规格压缩图片得到base64图片字符串
     *
     * @return
     */
    public static String resizeImage(String filePath) {
        try {
            int maxSize = 99; // kb
            BufferedImage src = fileToBufferedImage(filePath);
            int srcWdith = src.getWidth();
            int srcHeigth = src.getHeight();
            BufferedImage output = Thumbnails.of(src).size(srcWdith, srcHeigth).imageType(BufferedImage.TYPE_INT_RGB).asBufferedImage();

            //判断图片格式
            if (filePath!=null && filePath.length()>3) {
                String substring = filePath.substring(filePath.length() - 3);
                ImageFormat = substring;
            }
            String base64 = imageToBase64(output);
            while (base64.length() - base64.length() / 8 * 2 > maxSize * 1000) {
                output = Thumbnails.of(output).scale(0.9f).asBufferedImage();
                base64 = imageToBase64(output);
            }
            return base64;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 图片文件转BufferedImage
     *
     * @param filePath
     * @return
     * @throws Exception
     */
    public static BufferedImage fileToBufferedImage(String filePath) throws Exception {
        String path = filePath.substring(filePath.lastIndexOf("/") + 1,filePath.length());
        String encode = null;
        try {
            encode = URLEncoder.encode(path, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        filePath = filePath.substring(0,filePath.lastIndexOf("/") +1) + encode;

        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        byte[] buffer = null;
        BufferedImage img = null;
        try {
            //判断网络链接图片文件/本地目录图片文件
            if (filePath.startsWith("http://") || filePath.startsWith("https://")) {
                // 创建URL
                URL url = new URL(filePath);
                // 创建链接
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                inputStream = conn.getInputStream();
                outputStream = new ByteArrayOutputStream();
                // 将内容读取内存中
                buffer = new byte[1024];
                int len = -1;
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                buffer = outputStream.toByteArray();
            }
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buffer);
            img = ImageIO.read(byteArrayInputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return img;
    }

    /**
     * 将base64字符转换为输入流
     *
     * @param base64string
     * @return
     */
    private static InputStream base64StringToInputStream(String base64string) {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(base64string.getBytes());
        InputStream inputStream = byteArrayInputStream;
        return inputStream;
    }

    /**
     * 将BufferedImage转换为base64字符串
     *
     * @param bufferedImage
     * @return
     */
    public static String imageToBase64(BufferedImage bufferedImage) {
        Base64 encoder = new Base64();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage, ImageFormat, baos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(encoder.encode((baos.toByteArray())));
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值