图片在线url转base64


解决图片转换的跨域问题

@RequestMapping("/getPictureBase64ByUrl")
    @ResponseBody
    @ExceptionAnnotation
    public CommonResult getPictureBase64ByUrl(String url) {
        CommonResult result = new CommonResult();
        byte[] picByteData = getPicByteData(url);
        String picBase64Data = "data:image/jpg;base64," + Base64.getEncoder().encodeToString(picByteData);
        result.setRows(picBase64Data);
        return result;
    }

    private byte[] getPicByteData(String url) {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        try {
            connection = (HttpURLConnection) new URL(url).openConnection();

            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5 * 1000);
            inputStream = connection.getInputStream();
            outputStream = new ByteArrayOutputStream();
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }

            byte[] picData = outputStream.toByteArray();

            return picData;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                }
            }
        }
        return null;
    }

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM