gpt4 book ai didi

android - 如何将图像文件从 URL 下载到 ByteArray?

转载 作者:行者123 更新时间:2023-11-29 00:37:30 25 4
gpt4 key购买 nike

以下是我的代码:

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 为 null 而引起的。您需要先分配数组,然后才能将数据读入其中。

关于android - 如何将图像文件从 URL 下载到 ByteArray?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11708040/

25 4 0
文章推荐: android - 取消 AsyncTask
文章推荐: php - 根据特定条件将来自 my_MySQL 的值分组显示在单独的
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com