Skip to content

Instantly share code, notes, and snippets.

@jdamcd
Created December 6, 2012 12:52
Show Gist options
  • Save jdamcd/4224231 to your computer and use it in GitHub Desktop.
Save jdamcd/4224231 to your computer and use it in GitHub Desktop.
Thumbnail scaling for Android notfications
public class NotificationThumbnailHelper {
private float targetWidth;
private float targetHeight;
public NotificationThumbnailHelper(Context context) {
targetWidth = getTargetWidth(context);
targetHeight = getTargetHeight(context);
}
public Bitmap scaleBitmap(Bitmap input) {
if (input.getWidth() >= input.getHeight()) {
return scaleLandscapeThumbnail(input);
} else {
return scalePortraitThumbnail(input);
}
}
private Bitmap scaleLandscapeThumbnail(Bitmap input) {
float scale = targetHeight / input.getHeight();
int scaledWidth = (int) (input.getWidth() * scale);
Bitmap scaled = Bitmap.createScaledBitmap(input, scaledWidth, (int) targetHeight, true);
input.recycle();
return scaled;
}
private Bitmap scalePortraitThumbnail(Bitmap input) {
float scale = targetWidth / input.getWidth();
int scaledHeight = (int) (input.getHeight() * scale);
Bitmap scaled = Bitmap.createScaledBitmap(input, (int) targetWidth, scaledHeight, true);
input.recycle();
return scaled;
}
private float getTargetWidth(Context context) {
return context.getResources().getDimensionPixelSize(R.dimen.notification_large_icon_width);
}
private float getTargetHeight(Context context) {
return context.getResources().getDimensionPixelSize(R.dimen.notification_large_icon_height);
}
}
@rock3r
Copy link

rock3r commented Feb 12, 2013

A word of caution might be needed here: the input.recycle() means you have to create new Bitmaps when you want to use them in a Notification, because if you try to reuse for example some graphics you've got in your memcache you'll have them invalidated (and that's something you most likely don't want to do!)

@jdamcd
Copy link
Author

jdamcd commented Feb 16, 2013

Yeah. Absolutely. This code was based on an assumption that the input Bitmap is throw-away. Thanks for making that clear!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment