Android image didn't display to ImageView from

2019-07-11 02:59发布

I want to display image to ImageView from "http://i.imgur.com/4GLKF4Q.jpg" but The image in image URL didn't display to imageview. Can I do this?

AsyncTask

class DownloadImageTask extends AsyncTask<String, Void, byte[]> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected byte[] doInBackground(String... urls) {
        try {
            URL url = new URL(urls[0]);
            InputStream is = (InputStream) url.getContent();
            byte[] buffer = new byte[8192];
            int bytesRead;
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            while ((bytesRead = is.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }
            return output.toByteArray();
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    protected void onPostExecute(byte[] result) {
        ByteArrayInputStream imageStream = new ByteArrayInputStream(result);
        Bitmap bm = BitmapFactory.decodeStream(imageStream);
        bmImage.setImageBitmap(bm);
    }
}

in activity

new DownloadImageTask((ImageView) newView.findViewById(R.id.thumbnail))
            .execute("http://i.imgur.com/4GLKF4Q.jpg");

The image in image URL didn't display to imageview. in Logcat :

09-23 10:26:49.410 10591-10591/com.*** D/skia: --- SkImageDecoder::Factory returned null

3条回答
对你真心纯属浪费
2楼-- · 2019-07-11 03:46

Update from comment : changing image server to another one solve the issue. I guess it's a i.imgur.com issue.


You shouldn't use your own image loader task, it will leak somewhere. Two good library exist : - Fresco (from Facebook) - Picasso (from Square up)

There is also UniversalImageLoader (UIL).

查看更多
做自己的国王
3楼-- · 2019-07-11 03:52

Now there is an official way to load an ImageView from a URL and that is NOT to use an ImageView.

NetworkImageView—builds on ImageLoader and effectively replaces ImageView for situations where your image is being fetched over the network via URL. NetworkImageView also manages canceling pending requests if the view is detached from the hierarchy.

Images are automatically loaded in a background thread and the view updated on the UI thread. It even supports caching.

查看更多
4楼-- · 2019-07-11 03:55
  1. I would suggest you to checkout Image Management Library by Facebook that is Fresco that is pretty awesome and mature as compared to other Image Loading Library.

  2. Fresco handles all the things caching of images with 3 Tier architecture ( BITMAP_MEMORY_CACHE, ENCODED_MEMORY_CACHE and DISK_CACHE). It also reduces OOM(Out Of Memory) issues. When image in a view goes out of screen it automatically recycles the bitmap, hence releasing the memory.

查看更多
登录 后发表回答