Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use glide to load bitmap to ImageView

I would like to use Glide to load bitmap to ImageView after cropping and re-sizing a bitmap.

I don't want to use ImageView.setImageBitmap(bitmap); because I am loading lots of images and it might be taking up some memory, although the images are small in size, I just need to use Glide because I know it optimises image caching.

I read this post, but I didn't quite understand his solution when I tried implementing it. So maybe someone has a cleaner and more easily understandable solution.

This is my code which picks up an image and creates a bitmap out of it.

I need to use glide instead of ImageView.setImageBitmap(bitmap);.

new AsyncTask<String, Void, Void>() {
    Bitmap theBitmap = null;
    Bitmap bm = null;

    @Override
    protected Void doInBackground(String... params) {
        String TAG = "Error Message: ";
        try {
            //Load the image into bitmap
            theBitmap = Glide.
                    with(mContext).
                    load("http://example.com/imageurl").
                    asBitmap().
                    into(-1, -1).
                    get();

            //resizes the image to a smaller dimension out of the main image.
            bm = Bitmap.createBitmap(theBitmap, 0, 0, 210, 80);
        } catch (final ExecutionException e) {
            Log.e(TAG, e.getMessage());
        } catch (final InterruptedException e) {
            Log.e(TAG, e.getMessage());
        } catch (final NullPointerException e) {
            //
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void dummy) {
        if (null != theBitmap) {
            //Set image to imageview.
            **// I would like to Use Glide to set the image view here Instead of .setImageBitmap function**
            holder.mImageView.setImageBitmap(bm);

            holder.mImageView.setAdjustViewBounds(true);
            holder.mImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        }
    }
}.execute();
like image 712
Tosin Onikute Avatar asked Nov 14 '15 14:11

Tosin Onikute


1 Answers

You don't need AsyncTask to load image with Glide. Glide load image asynchronys. Try to use this code:

Glide.with(mContext)
                .load("http://example.com/imageurl")
                .asBitmap()
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        // you can do something with loaded bitmap here

                        // .....

                        holder.mImageView.setImageBitmap(resource);
                    }
                });
like image 128
Yuriy Kolbasinskiy Avatar answered Oct 09 '22 21:10

Yuriy Kolbasinskiy