BitmapFactory的decodeStream()方法导致InputStream失效的问题
问题代码:
FileOutputStream fos =null;
InputStream is=null;
try {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(“GET”);
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
is = new BufferedInputStream(conn.getInputStream());
Log.e(“string”,is.toString());
Log.e(“mark”,is.markSupported()+”“);
//因为需要二次读流,这里做一下标记
is.mark(is.available());
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds=true;
//注:decodeStream会使Input读流的时候mark标记失效
Bitmap bitmap = BitmapFactory.decodeStream(is,null,opts);
ImageSize imageSize =getImageViewSize(imageView);
opts.inSampleSize=caculateInSampleSize(opts,imageSize.width,imageSize.height);
opts.inJustDecodeBounds=false;
is.reset();
bitmap = BitmapFactory.decodeStream(is,null,opts);
conn.disconnect();
return bitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
解决办法:可以将流读入数组中,再从数组中读取。
代码如下:
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(“GET”);
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
if(conn.getResponseCode()!=200){
return null;
}
is = conn.getInputStream();
baos = new ByteArrayOutputStream();
byte [] bytes = new byte[1024];
int temp=0;
//把流写入baos
while ((temp=is.read(bytes))!=-1){
baos.write(bytes,0,temp);
}
is.close();
baos.close();
//数据放到数组中
byte[] data = baos.toByteArray();
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds=true;
Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length,opts);
// 注:decodeStream会使Input读流的时候mark标记失效
// Bitmap bitmap = BitmapFactory.decodeStream(is,null,opts);
ImageSize imageSize =getImageViewSize(imageView);
opts.inSampleSize=caculateInSampleSize(opts,imageSize.width,imageSize.height);
opts.inJustDecodeBounds=false;
bitmap = BitmapFactory.decodeByteArray(data,0,data.length,opts);
conn.disconnect();
return bitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;