图片在线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;
    }

  

上一篇:java io流(1)


下一篇:JAVA转HTTP地址图片时Base64结果不正确问题