java图片转base64和真实的结果不一样
迷茫
迷茫 2017-04-18 10:56:39
0
3
832

先上代码

        String imgURL = "http://www.g3zj.net:8082/util.action?method=appauthimg&d_=99";

        byte[] data = null;
        try {
            // 创建URL
            URL url = new URL(imgURL);
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();
            data = new byte[inStream.available()];
            inStream.read(data);
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        str=encoder.encode(data);

就是从一个网络读取图片并转成base64.发现转出来的结果无法用于img标签显示(已加了data:image/jpeg;base64,前缀)。
后来直接百度找了一个在线生成base64的网站,把这个图片url放上去转换,
结果发现别人在线转换出来的base64比我java代码转换的base64还长了很多。

为什么会这样呢?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(3)
黄舟

The value returned by available() of InputStream is the length of data that can be read at one time by the InputStream without being blocked. However, network conditions are always uncertain and often blocked. Therefore, it is recommended to use a loop to read the data in the InputStream.

伊谢尔伦

It is safer to read the entire InputStream时,用Streams.copy(). For example, in the title of the question, it can be:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
Streams.copy(conn.getInputStream(), baos);
String str = new BASE64Encoder(baos.toByteArray());
巴扎黑
 String imgURL = "http://www.g3zj.net:8082/util.action?method=appauthimg&d_=99";
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(imgURL);
            byte[] by = new byte[1024];
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream is = conn.getInputStream();
            // 将内容读取内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            // 关闭流
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        System.out.println("data:image/jpg;base64,"+encoder.encode(data.toByteArray()));

However, the poster’s code can be used. In my case, just add data:image/jpg;base64 and it will be fine

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template