Search code examples
androidpicassoandroid-glide

How to only scale-down an image if it is larger than requested size in Glide?


I have been using Picasso from a long time. Today, I am migrating to Glide. In Picasso, I used to use following loading pattern:

Picasso.get()
    .load(file)
    .resize(targetSize, 0)
    .onlyScaleDown()
    .placeholder(R.color.default_surface)
    .error(R.color.default_surface_error)
    .into(imageView)

According to resize(int, int) documentation,

Use 0 as desired dimension to resize keeping aspect ratio

According to onlyScaleDown() documentation,

Only resize an image if the original image size is bigger than the target size specified by resize(int, int)

Here's what I am trying:

Glide.with(imageView)
    .log(this, thumbnailUrl?.toString())
    .load(thumbnailUrl)
    .override(600)
    .placeholder(R.color.default_surface)
    .error(R.color.default_surface_error)
    .into(imageView)

Glide uses a default downsampling strategy when loading images using DownsampleStrategy.CENTER_OUTSIDE. It says that image is upscaled to match the overridden size such that one of the dimension (smallest?) is equal to overridden size. And, following comment:

Scales, maintaining the original aspect ratio, so that one of the image's dimensions is exactly equal to the requested size and the other dimension is greater than or equal to the requested size.

This method will upscale if the requested width and height are greater than the source width and height. To avoid upscaling, use {@link #AT_LEAST}, {@link #AT_MOST}, or {@link #CENTER_INSIDE}.

Options in DownsampleStrategy.java confused me. I don't know which one I should use. I want the large images to scale down to overridden size, and small images to never upscale. How to achieve this in Glide?


Solution

  • I have found an answer in Github Issue #3215 where following is suggested:

    Pick a useful DownsampleStrategy, in particular CENTER_INSIDE may be what you're looking for. The default DownsampleStrategy will upscale to maximimize Bitmap re-use, but typically there's an equivalent strategy available that will not upscale.

    And, DownsampleStrategy.CENTER_INSIDE fits what I wanted:

    Returns the original image if it is smaller than the target, otherwise it will be downscaled maintaining its original aspect ratio, so that one of the image's dimensions is exactly equal to the requested size and the other is less or equal than the requested size. Does not upscale if the requested dimensions are larger than the original dimensions.

    I was confused by the documentation for DownsampleStrategy.CENTER_INSIDE in code.