Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: Bitmap transformation with size limit #1017

Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,8 @@ public void onAfterUpdate(
.apply(FastImageViewConverter
.getOptions(context, imageSource, mSource)
.placeholder(mDefaultSource) // show until loaded
.fallback(mDefaultSource)); // null will not be treated as error
.fallback(mDefaultSource))
.transform(new ResizeTransformation());

if (key != null)
builder.listener(new FastImageRequestListener(key));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package com.dylanvann.fastimage;

import android.content.Context;
import android.graphics.Bitmap;

import androidx.annotation.NonNull;

import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.engine.Resource;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapResource;

import java.security.MessageDigest;

public class ResizeTransformation implements Transformation<Bitmap> {

private final double MAX_BYTES = 25000000.0;

@NonNull
@Override
public Resource<Bitmap> transform(@NonNull Context context, @NonNull Resource<Bitmap> resource, int outWidth, int outHeight) {
Bitmap toTransform = resource.get();

if (toTransform.getByteCount() > MAX_BYTES) {
double scaleFactor = Math.sqrt(MAX_BYTES / (double) toTransform.getByteCount());
int newHeight = (int) (outHeight * scaleFactor);
int newWidth = (int) (outWidth * scaleFactor);

BitmapPool pool = GlideApp.get(context).getBitmapPool();
Bitmap scaledBitmap = Bitmap.createScaledBitmap(toTransform, newWidth, newHeight, true);
return BitmapResource.obtain(scaledBitmap, pool);
}

return resource;
}

@Override
public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
messageDigest.update(("ResizeTransformation").getBytes());
}
}