Spring Boot 图片url转换为base64字符串

通过图片链接将图片转换为base64编码字符串

之前直接向前端传图片文件,遇到跨域问题,一直没有解决,干脆将图片的base64字符串给前端了
参数:String类型,imgurl 图片链接
返回值:String类型,编码后的字符串

    /**
     * 请求图片地址, 返回的结果进行base64编码
     * @param imgUrl 图片地址
     * @return
     */
    public static String requestUrlToBase64(String imgUrl) {
        String result = null;
        HttpURLConnection connection = null;

        try {
            URL url = new URL(imgUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            // 获取请求输入流
            InputStream inputStream = connection.getInputStream();
            // inputStream流数据转ByteArrayOutputStream
            int len = -1;
            byte[] buffer = new byte[1024];
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            while ((len = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }

            // ByteArrayOutputStream编码成base64字符串
            result = new String(Base64.getEncoder().encode(out.toByteArray()));
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(connection != null){
                connection.disconnect();
            }
        }

        return result;
    }

可以结合一些在线的图片转换工具进行测试
例如:http://tool.chinaz.com/tools/imgtobase
Spring Boot 图片url转换为base64字符串_第1张图片

你可能感兴趣的:(spring,boot)