先上代码
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还长了很多。
为什么会这样呢?
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:However, the poster’s code can be used. In my case, just add data:image/jpg;base64 and it will be fine