以下是我的代码:
private byte[] downloadImage(String image_url) {
byte[] image_blob = null;
URL _image_url = null;
HttpURLConnection conn = null;
InputStream inputStream = null;
try {
_image_url = new URL(image_url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
conn = (HttpURLConnection) _image_url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
conn.setDoInput(true);
try {
conn.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn.setUseCaches(false);
try {
inputStream = conn.getInputStream();
inputStream.read(image_blob);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn.disconnect();
}
return image_blob;
}
我想做的是获取图像的字节数组。在包裹中使用它可以将其转移到另一个 Activity 。
使用此代码会报告 NullPointerException。谁能说一下哪里出了问题吗?
最佳答案
您可能想像这样尝试:
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(imageUrl);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
int imageLength = (int)(entity.getContentLength());
InputStream is = entity.getContent();
byte[] imageBlob = new byte[imageLength];
int bytesRead = 0;
while (bytesRead < imageLength) {
int n = is.read(imageBlob, bytesRead, imageLength - bytesRead);
if (n <= 0)
; // do some error handling
bytesRead += n;
}
顺便说一句:NullPointerException 是因为image_blob
为空而引起的。您需要先分配数组,然后才能将数据读入其中。
关于android - 如何将图像文件从 URL 下载到 ByteArray?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11708040/