您的位置:首页 > 其它

BitmapFactory的decodeStream()方法导致InputStream失效的问题

2017-03-22 10:48 183 查看
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;


参考链接:http://www.xue163.com/2653/1/26535657_4.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: