Skip to content

Instantly share code, notes, and snippets.

@ryupold
Created August 10, 2015 14:20
Show Gist options
  • Save ryupold/3aa90654bcb5509b3cbf to your computer and use it in GitHub Desktop.
Save ryupold/3aa90654bcb5509b3cbf to your computer and use it in GitHub Desktop.
create thumbnail of large BitmapImage (Android/Xamarin)
public Bitmap GetThumbnail(Uri uri, int thumbnailSize)
{
var input = this.ContentResolver.OpenInputStream(uri);
BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
onlyBoundsOptions.InJustDecodeBounds = true;
onlyBoundsOptions.InDither = true; //optional
onlyBoundsOptions.InPreferredConfig = Bitmap.Config.Argb8888; //optional
BitmapFactory.DecodeStream(input, null, onlyBoundsOptions);
input.Close();
if ((onlyBoundsOptions.OutWidth == -1) || (onlyBoundsOptions.OutHeight == -1))
return null;
int originalSize = (onlyBoundsOptions.OutHeight > onlyBoundsOptions.OutWidth)
? onlyBoundsOptions.OutHeight
: onlyBoundsOptions.OutWidth;
double ratio = (originalSize > thumbnailSize) ? (originalSize / thumbnailSize) : 1.0;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.InSampleSize = GetPowerOfTwoForSampleRatio(ratio);
bitmapOptions.InDither = true; //optional
bitmapOptions.InPreferredConfig = Bitmap.Config.Argb8888; //optional
input = this.ContentResolver.OpenInputStream(uri);
Bitmap bitmap = BitmapFactory.DecodeStream(input, null, bitmapOptions);
input.Close();
return bitmap;
}
private static int GetPowerOfTwoForSampleRatio(double ratio)
{
int k = Integer.HighestOneBit((int)Math.Floor(ratio));
if (k == 0) return 1;
else return k;
}
@ryupold
Copy link
Author

ryupold commented Aug 10, 2015

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