Converting image url to bitmap quickly

后端 未结 3 1398
[愿得一人]
[愿得一人] 2021-02-10 06:01

I need to display the list of images from api in the list page. For that i used two approaches.

First Approach:
By converting the url to byte array

3条回答
  •  -上瘾入骨i
    2021-02-10 06:23

    There are open-source libraries which focus on loading image into an ImageView. Take for example of universal-image-loader, it is very easy to use, like:

    // Load image, decode it to Bitmap and display Bitmap in ImageView (or any other view 
    //  which implements ImageAware interface)
    imageLoader.displayImage(imageUri, imageView);
    

    or:

    // Load image, decode it to Bitmap and return Bitmap to callback
    imageLoader.loadImage(imageUri, new SimpleImageLoadingListener() {
        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            // Do whatever you want with Bitmap
        }
    });
    

    or:

    // Load image, decode it to Bitmap and return Bitmap synchronously
    Bitmap bmp = imageLoader.loadImageSync(imageUri);
    

    Take example of Volley, you can use it like this:

    public void displayImg(View view){
        ImageView imageView = (ImageView)this.findViewById(R.id.image_view);
        RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext()); 
    
        ImageLoader imageLoader = new ImageLoader(mQueue, new BitmapCache());
    
        ImageListener listener = ImageLoader.getImageListener(imageView,R.drawable.default_image, R.drawable.default_image);
        imageLoader.get("http://developer.android.com/images/home/aw_dac.png", listener);
        //指定图片允许的最大宽度和高度
        //imageLoader.get("http://developer.android.com/images/home/aw_dac.png",listener, 200, 200);
    }
    

    These libraries are used broadly, and more importantly, they are open-sourced. No need to implement functions like this repeatedly.

提交回复
热议问题