1. 程式人生 > >BitmapFactory.decodeStream 返回值為null的問題

BitmapFactory.decodeStream 返回值為null的問題

  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();
	}