先上代碼
String imgURL = "http://www.g3zj.net:8082/util.action?method=appauthimg&d_=99";
byte[] data = null;
try {
// 創(chuàng)建URL
URL url = new URL(imgURL);
// 創(chuàng)建鏈接
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();
}
// 對字節(jié)數(shù)組Base64編碼
BASE64Encoder encoder = new BASE64Encoder();
str=encoder.encode(data);
就是從一個網(wǎng)絡(luò)讀取圖片并轉(zhuǎn)成base64.發(fā)現(xiàn)轉(zhuǎn)出來的結(jié)果無法用于img標簽顯示(已加了data:image/jpeg;base64,前綴)。
后來直接百度找了一個在線生成base64的網(wǎng)站,把這個圖片url放上去轉(zhuǎn)換,
結(jié)果發(fā)現(xiàn)別人在線轉(zhuǎn)換出來的base64比我java代碼轉(zhuǎn)換的base64還長了很多。
為什么會這樣呢?
業(yè)精于勤,荒于嬉;行成于思,毀于隨。
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 {
// 創(chuàng)建URL
URL url = new URL(imgURL);
byte[] by = new byte[1024];
// 創(chuàng)建鏈接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream is = conn.getInputStream();
// 將內(nèi)容讀取內(nèi)存中
int len = -1;
while ((len = is.read(by)) != -1) {
data.write(by, 0, len);
}
// 關(guān)閉流
is.close();
} catch (IOException e) {
e.printStackTrace();
}
// 對字節(jié)數(shù)組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