Now that you have a quick low-down on the issues, here is a method that will take a URI and down-sample it to a more manageable size by a factor (int num) you choose.
/**
* Resamples the Bitmap read from file to get a smaller size to
* prevent OutofMemory Errors
* @param imageUri
* @return bitmap
*/
public Bitmap resampleBitmap (Uri imageUri, int num){
ContentResolver cr = getContentResolver();
Bitmap bitmap = null;
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inSampleSize = num;
AssetFileDescriptor file = cr.openAssetFileDescriptor(imageUri, "r");
bitmap = BitmapFactory.decodeFileDescriptor(file.getFileDescriptor(),
null, options);
} catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
return bitmap;
}
Obviously quick and dirty but it should put you on your way out of the dreaded OutofMemory error. We will look at more ways to deal with large images efficiently in future posts.
For now note you can calculate an inSampleSize base on the size of the image. If you plan to use this method in several activities, a better idea is to make it into a static method of a helper/utility class, passing in instance specific information via parameters.
No comments:
Post a Comment