您的位置:首页 > 移动开发 > Android开发

解决android BitmapFactory.decodeStream()返回null

2014-05-04 22:11 477 查看
问题代码:
private Bitmap downloadBitmap(String imageUrl) {
Bitmap bitmap = null;
HttpURLConnection con = null;
try {
URL url = new URL(imageUrl);
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5 * 1000);
con.setReadTimeout(10 * 1000);
con.setDoInput(true);
con.setDoOutput(true);
//这里返回的bitmap=null
bitmap = BitmapFactory.decodeStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
con.disconnect();
}
}
return bitmap;
}

解决办法:
public byte[] getBytes(InputStream is) throws IOException {
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = is.read(buffer)) != -1) {
outstream.write(buffer, 0, len);
}
outstream.close();
return outstream.toByteArray();
}

public byte[] InputStreamTOByte(InputStream in) throws IOException{

ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int count = -1;
while((count = in.read(data,0,1024)) != -1)
outStream.write(data, 0, count);

data = null;
return outStream.toByteArray();
}

byte[] data = InputStreamTOByte(new URL(imgUrl).openStream());
Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: