参考博客:https://blog.csdn.net/changerzhuo_319/article/details/70161387
读取远程图片时,读不全,图片只读到一部分,怎么回事呢?
这就是网络上读取时丢包了。
怎么样才能读取完整的图片呢?
其实很简单,控制好读完才停止。怎么确定读完了呢。连接有个方法获取远程资源的长度–getContentLength()
具体代码如下:
public static String urlToString(String imgUrl){
byte[] result=null;
InputStream inStream=null;
String photo = "";
try {
//创建URL
URL url=new URL(imgUrl);
//创建连接
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5*1000);
inStream=conn.getInputStream();
int count=conn.getContentLength();//获取远程资源长度
result=new byte[count];
int readCount=0;
while(readCount<count){//循环读取数据
readCount+=inStream.read(result,readCount,count-readCount);
}
photo = toBase64(result);
} catch (Exception e) {
e.printStackTrace();
log.error("获取远程图片失败", e);
} finally {
try {
if (inStream != null) {
inStream.close();
}
} catch (IOException e) {
log.error("文件处理错误!", e);
}
log.info("o==||=====>读取图片返回");
}
return photo;
}
private static String toBase64(byte[] imgData) {
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(imgData);
}