Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop Glide upscaling?

I am using the Glide image loading library and I'm having issues when it comes to resizing bitmaps.

When using the following code:

Glide.with(getActivity())
    .load(images.get(i))
    .asBitmap().centerCrop()
    .into(new SimpleTarget<Bitmap>(1200, 1200) {
        @Override
        public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {

        }
    });

Every single bitmap gets resized to the specified dimensions. So, if the image is 400x300, it gets upscaled up to 1200 x 1200 which I do not want. How do I make it so that if the image is smaller than the specified dimensions, it won't resize it?

I'm specifying dimensions because I want every image that's bigger than the specified dimensions to be resized taking into account centerCrop; and then if the image is smaller than the specified dimensions, I don't want it to be resized.

like image 695
Jack Avatar asked Apr 18 '16 17:04

Jack


1 Answers

I want every image that's bigger than the specified dimensions to be resized taking into account centerCrop; and then if the image is smaller than the specified dimensions, I don't want it to be resized.

You can obtain this behaviour with a custom transformation:

public class CustomCenterCrop extends CenterCrop {

    public CustomCenterCrop(BitmapPool bitmapPool) {
        super(bitmapPool);
    }

    public CustomCenterCrop(Context context) {
        super(context);
    }

    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        if (toTransform.getHeight() > outHeight || toTransform.getWidth() > outWidth) {
            return super.transform(pool, toTransform, outWidth, outHeight);
        } else {
            return toTransform;
        }
    }
}

and then use it like this:

Glide.with(getActivity())
    .load(images.get(i))
    .asBitmap()
    .transform(new CustomCenterCrop(getActivity()))
    .into(new SimpleTarget<Bitmap>(1200, 1200) {
        @Override
        public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {

        }
    });
like image 165
Mattia Maestrini Avatar answered Sep 30 '22 16:09

Mattia Maestrini