通过AsyncTask下载图像并将其显示在Imageview中而不存储在SD卡中

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通过AsyncTask下载图像并将其显示在Imageview中而不存储在SD卡中相关的知识,希望对你有一定的参考价值。

我想通过AsyncTask下载图像并希望在ImageView中显示它我能够正常地执行它但我还想向用户显示进度并完成所有这些而无需将文件存储在SD卡中。

这是我到目前为止所做的。

class DownloadFileFromURL extends AsyncTask<String, String, String> {

/**
 * Before starting background thread
 * Show Progress Bar Dialog
 * */
@Override
protected void onPreExecute() {
    super.onPreExecute();
    showDialog(progress_bar_type);
}

/**
 * Downloading file in background thread
 * */
@Override
protected String doInBackground(String... f_url) {
    int count;
    try {
        URL url = new URL(f_url[0]);
        URLConnection conection = url.openConnection();
        conection.connect();
        // getting file length
        int lenghtOfFile = conection.getContentLength();

        // input stream to read file - with 8k buffer
        InputStream input = new BufferedInputStream(url.openStream(), 8192);

        // Output stream to write file
        OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");

        byte data[] = new byte[1024];

        long total = 0;

        while ((count = input.read(data)) != -1) {
            total += count;
            // publishing the progress....
            // After this onProgressUpdate will be called
            publishProgress(""+(int)((total*100)/lenghtOfFile));

            // writing data to file
            output.write(data, 0, count);
        }

        // flushing output
        output.flush();

        // closing streams
        output.close();
        input.close();

    } catch (Exception e) {
        Log.e("Error: ", e.getMessage());
    }

    return null;
}

/**
 * Updating progress bar
 * */
protected void onProgressUpdate(String... progress) {
    // setting progress percentage
    pDialog.setProgress(Integer.parseInt(progress[0]));
}

/**
 * After completing background task
 * Dismiss the progress dialog
 * **/
@Override
protected void onPostExecute(String file_url) {
    // dismiss the dialog after the file was downloaded
    dismissDialog(progress_bar_type);

    // Displaying downloaded image into image view
    // Reading image path from sdcard
    String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
    // setting downloaded into image view
    my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}

}
答案

如果您不想在本地下载图像,则应使用ByteArrayOutputStream而不是FileOutputStream

这是关键代码:

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
    total += count;
    publishProgress(""+(int)((total*100)/lenghtOfFile));

    outputStream.write(data, 0, count);
}

//after downloading the image
byte[] imageData = outputStream.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
my_image.setImageBitmap(bitmap);

我没有测试它,但我相信这可以帮助你。

另一答案

参考Best method to download image from url in Android

private Bitmap downloadBitmap(String url) {
        HttpURLConnection urlConnection = null;
        try {
            URL uri = new URL(url);
            urlConnection = (HttpURLConnection) uri.openConnection();

            int statusCode = urlConnection.getResponseCode();
            if (statusCode != HttpStatus.SC_OK) {
                return null;
            }

            InputStream inputStream = urlConnection.getInputStream();
            if (inputStream != null) {

                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                return bitmap;
            }
        } catch (Exception e) {
            Log.d("URLCONNECTIONERROR", e.toString());
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            Log.w("ImageDownloader", "Error downloading image from " + url);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();

            }
        }
        return null;
    }
另一答案

您可以使用Glide代替:

Glide.with(this).load("http://server.com/image.jpg").into(imageView);

以上是关于通过AsyncTask下载图像并将其显示在Imageview中而不存储在SD卡中的主要内容,如果未能解决你的问题,请参考以下文章

Android - 在显示进度时将图像从 URL 加载到 ImageView(不保存图像)

Android AsyncTask 等待完成以检索数据并将其显示在 ListView

Android:需要一个使用的想法:Service、Thread、AsyncTask 或其他东西

NullPointerException 与 android AsyncTask 和 RecyclerView

Android 捕获和显示图像应用程序

从网络加载图像并将其显示在集合视图中