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

标签 android image download

以下是我的代码:

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/

相关文章:

python - 将 Numpy 数组转换为图像

javascript - 简单的褪色图像交换

ios - 图片下载间歇性

android - 无法使用 LibGDX Net 在 Android 上下载 100mb 文件

php - 防止共享下载 URL

一个TextView中的Android Spannable多个setSpan

node.js - Azure Functions,缩略图尺寸大于原始图像

java - 确定多边形是否在 map 边界内

android - 构建 Appbundle (Flutter) 时 keystore 密码不正确

java - AdMob libGDX 与 Google Play 服务