Bitmap android.graphics.BitmapFactory.decodeStream(InputStream is) public static Bitmap decodeStream (InputStream is) Since: API Level 1 Decode an input stream into a bitmap. If the input stream is null, or cannot be used to decode a bitmap, the function returns null. The stream's position will be where ever it was after the encoded data was read. Parameters is The input stream that holds the raw data to be decoded into a bitmap. Returns The decoded bitmap, or null if the image data could not be decoded.
注意黑体字。以下是具体代码:
public static Bitmap bmpFromURL(URL imageURL){ Bitmap result = null; try { HttpURLConnection connection = (HttpURLConnection)imageURL .openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); result = BitmapFactory.decodeStream(input); } catch (IOException e) { e.printStackTrace(); } return result; }后来调试发现,result为null,加之查看帮助文档中的黑体字,
后来在一篇文章中才发现,原来这是android 1.6版本的一个bug!
有牛人提出的一个解决办法,我试了试,问题解决了
首先在原方法中改一句:
result = BitmapFactory.decodeStream(new PatchInputStream(input));
public class PatchInputStream extends FilterInputStream{ protected PatchInputStream(InputStream in) { super(in); // TODO Auto-generated constructor stub } public long skip(long n)throws IOException{ long m=0l; while(m<n){ long _m=in.skip(n-m); if(_m==0l){ break; } m+=_m; } return m; } }
第二种方法:最终用的是这种方法
InputStream is = httpConn.getInputStream();
if (is == null){ throw new RuntimeException("stream is null"); }else{ try { byte[] data=readStream(is); if(data!=null){ bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); } } catch (Exception e) { e.printStackTrace(); } is.close(); }
/* * 得到图片字节流 数组大小 * */ public static byte[] readStream(InputStream inStream) throws Exception{ ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while( (len=inStream.read(buffer)) != -1){ outStream.write(buffer, 0, len); } outStream.close(); inStream.close(); return outStream.toByteArray(); }