今天碰到了一个超级恶心的问题,BitmapFactory.decodeStream(bis,null,options)一直是返回NULL
问题是这样子的:
1 InputStream is= response.body().byteStream(); 2 Bitmap bm; 3 BitmapFactory.Options options=new BitmapFactory.Options(); 4 options.inJustDecodeBounds=true; 5 6 BitmapFactory.decodeStream(is,null,options); 7 8 int screenWidth=getActivity().getWindowManager().getDefaultDisplay().getWidth(); 9 int screenHeight=getActivity().getWindowManager().getDefaultDisplay().getHeight(); 10 11 int widthScale=options.outWidth/screenWidth; 12 int heightScale=options.outHeight/screenHeight; 13 14 15 int scale=widthScale>heightScale?widthScale:heightScale; 16 options.inJustDecodeBounds=false; 17 options.inSampleSize=scale; 18 try { 19 bm=BitmapFactory.decodeStream(is,null,options); 20 image.setImageBitmap(bm); 21 is.close(); 22 23 } catch (Exception e) { 24 e.printStackTrace(); 25 }
第19行返回的位图始终为NULL,各种纠结百度(原谅我没有翻墙工具,吐槽下之前用的旗舰VPN,简直就是个黑店,买了一年的会员,居然特么倒闭了!!!)
发现因为之前的inputstream流已经被使用过了,导致指针往后移动,所以再次读取的时候就读不到数据了,
使用is.reset();就可以了,但是,这边还有个坑。。。。。。
一开始使用这个直接报IO异常了
后来发现,要想使用这个,首先,你的流 is.markSupported()必须返回true,
InputStream is= response.body().byteStream(); BufferedInputStream bis=new BufferedInputStream(is);//用BufferedInputStream包装Inputstream Bitmap bm; BitmapFactory.Options options=new BitmapFactory.Options(); options.inJustDecodeBounds=true; BitmapFactory.decodeStream(bis,null,options); int screenWidth=getActivity().getWindowManager().getDefaultDisplay().getWidth(); int screenHeight=getActivity().getWindowManager().getDefaultDisplay().getHeight(); int widthScale=options.outWidth/screenWidth; int heightScale=options.outHeight/screenHeight; int scale=widthScale>heightScale?widthScale:heightScale; options.inJustDecodeBounds=false; options.inSampleSize=scale; try { bis.reset();//重置 bm=BitmapFactory.decodeStream(bis,null,options); image.setImageBitmap(bm); is.close(); } catch (Exception e) { e.printStackTrace(); }
说是还有其他的解决办法,将inputstream解析成字节数组,使用decodeByteArray来解析,我试了下貌似也没用。。。。。
更新:
用上面的方法,会有一个比较坑的情况,请求图片过多,发现reset()报错,catch住之后就显示不了图片了。
然后还是用decodeByteArray吧。。。。
将inputStream转成 byte[]
private byte[] getByteArrayFromInputStream(InputStream is){ ByteArrayOutputStream bos=new ByteArrayOutputStream(); byte[] buffer=new byte[1024]; int len=0; try { while ((len=is.read(buffer))!=-1){ bos.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); }finally { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } return bos.toByteArray(); }
两次decode均使用decodeByteArray(),搞定!!!!弄死人的节奏啊。。。。。