Skip to content

Instantly share code, notes, and snippets.

@joaocsousa
Last active August 29, 2015 14:07
Show Gist options
  • Save joaocsousa/3e97297e4fa6cc4d75f5 to your computer and use it in GitHub Desktop.
Save joaocsousa/3e97297e4fa6cc4d75f5 to your computer and use it in GitHub Desktop.
Android snippet to load images and downscale if needed
import static android.graphics.BitmapFactory.decodeResource;
import static com.google.common.base.Optional.fromNullable;
public static final Double MAX_MEMORY_ALLOCATION = 6E6;
/**
* This method loads a bitmap from the resources respecting the max memory an image should take in memory
* @param imageResource
* @param context
* @return
*/
public static Optional<Drawable> loadDrawable(@DrawableRes int imageResource, Context context) {
Optional<Bitmap> candidateBitmap = loadBitmap(imageResource, context);
Optional<Drawable> candidateDrawable = absent();
if (candidateBitmap.isPresent()) {
candidateDrawable = fromNullable((Drawable) new BitmapDrawable(context.getResources(), candidateBitmap.get()));
}
return candidateDrawable;
}
/**
* This method loads a bitmap from the resources respecting the max memory an image should take in memory
* @param imageResource
* @param context
* @return
*/
public static Optional<Bitmap> loadBitmap(@DrawableRes int imageResource, Context context) {
BitmapFactory.Options scaledOptions = getScaledOptions(imageResource, context, MAX_MEMORY_ALLOCATION);
if (scaledOptions != null) {
scaledOptions.inJustDecodeBounds = false;
}
return fromNullable(decodeResource(context.getResources(), imageResource, scaledOptions));
}
/**
* Get the scale factor necessary to make an image take targetMaxMemory
* @param image
* @param context
* @param targetMemory
* @return
*/
public static BitmapFactory.Options getScaledOptions(@DrawableRes int image, Context context, double targetMemory) {
int scaleFactor = 1;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
decodeResource(context.getResources(), image, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
if (imageHeight != -1 && imageWidth != -1) {
int bytes = -1;
switch (options.inPreferredConfig) {
case ALPHA_8:
bytes = 1;
break;
case ARGB_4444:
case RGB_565:
bytes = 2;
break;
case ARGB_8888:
bytes = 4;
break;
}
while (imageWidth * imageHeight * bytes > targetMemory) {
imageWidth /= 2;
imageHeight /= 2;
scaleFactor *= 2;
}
}
options.inSampleSize = scaleFactor;
return options;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment