BitmapFactory.decodeStream 返回值为null的问题

来源:互联网 发布:南华大学船山学院 知乎 编辑:程序博客网 时间:2024/05/22 15:32

  public void download(String u) throws Exception {        URL url = new URL(u);        HttpURLConnection conn = (HttpURLConnection) url.openConnection();  conn.setConnectTimeout(5 * 1000);  conn.setRequestMethod("GET");        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {    InputStream is = conn.getInputStream();            Bitmap bitmap = BitmapFactory.decodeStream(is);        }    }


上面的代码中 BitmapFactory.decodeStream 返回了null,

后来看了一篇帖子说 android 1.6版本会有这样一个bug,虽然我用的不是1.6版本的,但是决定试一下,用高手建议的方法发现问题解决了


我的最终解决办法是:

public void download(String u) throws Exception {URL url = new URL(u);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setConnectTimeout(5 * 1000);conn.setRequestMethod("GET");if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {InputStream is = conn.getInputStream();byte[] data = reads(is);Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);}}public static byte[] reads(InputStream ins) throws Exception {ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] b = new byte[1024];int len = 0;while ((len = ins.read(b)) != -1) {outStream.write(b, 0, len);}outStream.close();ins.close();return outStream.toByteArray();}


原创粉丝点击