I have a problem when I take a photo with the camera in some devices and versions of Android. For example, in my Xperia U v4.0.3 my code works good but in another xperia U v2.3.3 it doesn't work...
I read a lot of about this error but I couldn't fix it...
My code to take a photo and show it:
public void callCamera(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, SELECT_CAMERA);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SELECT_CAMERA) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ContentResolver cr = getContentResolver();
try {
imageSelected = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
// I tried to read the image created for the camera in the Sd
//But I've got the same error...
//imageSelected = Utils.readImageSD(this, selectedImage.getPath());
imageSelected = Utils.rotateImage(Utils.scaleBitmap(imageSelected, 160, 160));
ivImageLoad.setImageBitmap(imageSelected);
} catch (Exception e) {
Utils.showToast(getApplicationContext(), R.string.errorLoad);
Log.e("Camera", e.toString());
}
}
}
I hope somebody can help me... I don't know what can I do....
Thanks in advance.
Regards.
It looks like you only want to display a 160x160 bitmap, but on this line you are reading in the whole bitmap and then later scaling it down.
imageSelected = android.provider.MediaStore.Images.Media(cr, selectedImage);
You can avoid ever loading the whole bitmap into memory by using inJustDecodeBounds, and then you can scale it using inSampleSize.
Here is some example code from the Android series on Loading Large Bitmaps Efficiently
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromUri(Uri uri,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
}
Then to get your 160x160 image you would just do:
ivImageLoad.setImageBitmap(decodeSampledBitmapFromUri(selectedImage, 100, 100));
Maybe the origin of the problem is the default Heap size. There are ways to increase it:
For Android 2.2 or lower versions:
dalvik.system.VMRuntime.getRuntime().setMinimumHeapSize(sizeInBytes);
For Android 2.3 or or higher versions:
android:largeHeap="true"
Check if the source of the problem is this, increasing the heap accordingly.
Related
How to decode bitmaps from Asset directory in Android 7?
My App is running well on Android versions up to Marshmallow. With Android 7 it fails to load images from the Asset directory.
My Code:
private Bitmap getImage(String imagename) {
// Log.dd(logger, "AsyncImageLoader: " + ORDNER_IMAGES + imagename);
AssetManager asset = context.getAssets();
InputStream is = null;
try {
is = asset.open(ORDNER_IMAGES + imagename);
} catch (IOException e) {
// Log.de(logger, "image konnte nicht gelesen werden: " + ORDNER_IMAGES + imagename);
return null;
}
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, PW, PH);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
// Lesen des Bitmaps in der optimierten Groesse
return BitmapFactory.decodeStream(is, null, options);
}
As a result (only Android 7) BitmapFactory.decodeStream is null. It works correctly an older Android APIs.
In debug mode I see the following Message:
09-04 10:10:50.384 6274-6610/myapp D/skia: --- SkAndroidCodec::NewFromStream returned null
Can someone tell me the reason and how to correct the coding?
Edit: Meanwhile i found, that removing of the first BitmapFactory.decodeStream with inJustDecodeBounds=true leads to a successful BitmapFactory.decodeStream afterwards with inJustDecodeBounds=false. Don't know the reason and don't know how to substitute the measurement of bitmap size.
I think we are in the same boat. My team stuck in this problem for a while like you.
It seems be a problem in BitmapFactory.cpp (https://android.googlesource.com/platform/frameworks/base.git/+/master/core/jni/android/graphics/BitmapFactory.cpp) Some code was added in Android 7.0 and made the problem occurred.
// Create the codec.
NinePatchPeeker peeker;
std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::NewFromStream(streamDeleter.release(), &peeker));
if (!codec.get()) {
return nullObjectReturn("SkAndroidCodec::NewFromStream returned null");
}
And I found out the BitmapFactory.decodeStream method didn't create the bitmap after we set inJustDecodeBounds=false but when I try to create bitmap without bound decoding. It's works! The problem is about BitmapOptions in that InputStream doesn't updated when we called BitmapFactory.decodeStream again.
So I reset that InputStream before decode again
private Bitmap getBitmapFromAssets(Context context, String fileName, int width, int height) {
AssetManager asset = context.getAssets();
InputStream is;
try {
is = asset.open(fileName);
} catch (IOException e) {
return null;
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, options);
try {
is.reset();
} catch (IOException e) {
return null;
}
options.inSampleSize = calculateInSampleSize(options, width, height);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(is, null, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
It's looks like we have to reset InputStream every time before reuse it.
I suspect the android default security config is not letting you download a file using protocol "http://" (no encryption).
Try finding an image or file with an "https://" protocol. See if that causes your file to load. Otherwise, set a Network Security Config that allows "http".
In case this helps anyone, I was bumping up against a similar issue updating older code that had previously worked for resizing images. My issue was further up the stack where I was reading data from the image file. I made use of IOUtils.toByteArray(Reader), which has been deprecated. I switched to converting to a byte array directly from the URI and now it is working well. See the first two lines of resizeImage() below for the example of that new method (The rest of the code allows me to resize the image.)
public static Bitmap resizeImage(Uri imageUri, int targetWidth, int targetHeight) {
// Convert the image to a byte array
java.net.URI tempUri = new URI(uri.toString());
byte[] imageData = IOUtils.toByteArray(tempUri);
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(imageData, 0, imageData.length, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, targetWidth, targetHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap reducedBitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length, options);
Bitmap resizedBitmap = Bitmap.createScaledBitmap(reducedBitmap, targetWidth, targetHeight, false);
return resizedBitmap;
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a
// power of 2 and keeps both height and width larger
// than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
Steps my application performs:-
Download a large no of images and save them on the SDCard.
Load every image into Bitmap and resize them, after resizing replace this resized image with the original one.
My code:-
Bitmap myimage = loadimage(path+temppos+".jpg");
Bitmap finalimage = getResizedBitmap(myimage,width,height);
//save image
.....
//recyclebitmap
myimage.recycle();
finalimage.recycle();
loadimage:-
public Bitmap loadimage(String path)
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inDither=true;
options.inPurgeable=true;
options.inInputShareable=true;
return BitmapFactory.decodeFile(path, options);
}
Now I' populating these images on gridview.
Output(Before):-
Output (After):-
Where Before corresponds to initially when only a few images are downloaded.
And After corresponds to after all the images are downloaded.
Now, I think it is happening maybe because of Bitmap.recycle() method but don't know the reason. Please correct me if I am wrong and point out the error here.
Edit: I must add the grid view shows around 50 downloaded images, but only the first three images are becoming unrecognizable.
Thanks.
For getting your resized Bitmap you can use the below code: (taken from this tutorial)
public static Bitmap decodeSampledBitmapFromPath(String path, int reqWidth,
int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bmp = BitmapFactory.decodeFile(path, options);
return bmp;
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
You can also take a look at the official site for getting a hint on loading Bitmaps
Edit
Try to change bitmap configuration to ARGB_8888 for best quality
because RGB_565 configuration can produce slight visual artifacts depending on the configuration of the source (taken from docs)
Update
I think you can take a look at this answer , I think this would solve your problem
I Need to Convert Bitmap to Byte Array Inorder to Upload to server i was able to achieve the same by converting Bitmap to Byte Array and again converting it to Base 64 String by following instructions here it worked well but in the worst case in my galaxy s2 mobile if the image size is of 6MB with 72 Pixels/Inch Resolution it is occupying around 600MB of RAM and app getting crash with OutOfMemoryException, i tried to upload by compressing the bitmap it worked fine but in my project requirement i need to upload the image as is i.e. with out any compression the original image
please help me how to achieve this whether it is possible or not
Thanks in Advance
For uploading convert to jpeg stream
BufferedStream bs = //...
then call bitmap.compress("JPEG", 0, length, bs)
convert bs to array ad upload that to server
Android application allocations memory heap is something limited. especially on low ram memory devices.
you are doing two different common mistakes:
first: regarding the upload issue - you are holding Bitmap object of a full size image (probably captured with the camera) . this is mistake at the first place. if you have to show on the user interface the captured image - you should load scaled version bitmap according to the required display size(the ImageView width and height..) from the captured image file that just captured and created:
public static Bitmap getSampleBitmapFromFile(String bitmapFilePath, int reqWidth, int reqHeight) {
try {
File f = new File(bitmapFilePath);
ExifInterface exif = new ExifInterface(f.getPath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int angle = 0;
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
angle = 90;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
angle = 180;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
angle = 270;
}
Matrix mat = new Matrix();
mat.postRotate(angle);
// calculating image size
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, options);
int scale = calculateInSampleSize(options, reqWidth, reqHeight);
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
Bitmap correctBmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), mat, true);
return correctBmp;
} catch (IOException e) {
Log.e(TAG, "cant butmaputils.getSampleBitmapFromFile failed with IO exception: ", e);
if (e != null)
e.printStackTrace();
} catch (OutOfMemoryError oom) {
Log.e(TAG, "cant butmaputils.getSampleBitmapFromFile failed with OOM error: ");
if (oom != null)
oom.printStackTrace();
} catch (Exception e) {
Log.e(TAG, "cant butmaputils.getSampleBitmapFromFile failed with exception: ", e);
}
Log.e(TAG, "butmaputils.getSampleBitmapFromFilereturn null for file: " + bitmapFilePath);
return null;
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
by that alone - you reduce dramatically the pressure on your memory allocation heap, because instead of allocation (for example) 1080x1920 integers, you could allocate just 100x200 if that's your imageView screen dimentions.
second: uploading to server: you should upload to your server a direct stream from the large original file instead of loading it to memory as Bitmap + decode it to base 64 or. the best way to do it is by using Multipart Entity.
using this approch, not limiting you at all, and even if you want to upload 100M-1000M file - it does not matters, and don't have impact on the memory allocation heap.
for more reading, I recommend you to read - http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
When I try to get image from camera or gallery, I get error. Here is a part of logcat:
06-27 05:51:47.297: E/dalvikvm-heap(438): Out of memory on a 35295376-byte allocation.
06-27 05:51:47.312: E/dalvikvm(438): Out of memory: Heap Size=108067KB, Allocated=71442KB, Limit=131072KB
06-27 05:51:47.312: E/dalvikvm(438): Extra info: Footprint=108067KB, Allowed Footprint=108067KB, Trimmed=56296KB
06-27 05:51:47.312: E/PowerManagerService(438): Excessive delay when setting lcd brightness: mLcdLight.setBrightness(176, 1) spend 288ms, mask=2
06-27 05:51:48.052: E/dalvikvm-heap(4332): Out of memory on a 24023056-byte allocation.
06-27 05:51:48.057: E/dalvikvm(4332): Out of memory: Heap Size=63139KB, Allocated=40922KB, Limit=65536KB
06-27 05:51:48.057: E/dalvikvm(4332): Extra info: Footprint=63139KB, Allowed Footprint=63139KB, Trimmed=0KB
06-27 05:51:48.057: E/EmbeddedLogger(438): App crashed! Process: <my_app_name>
Here is my code that provides me to take an image:
Intent pickIntent = new Intent();
pickIntent.setType("image/*");
pickIntent.setAction(Intent.ACTION_GET_CONTENT);
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Intent chooserIntent = Intent.createChooser(pickIntent, "Select or take a new Picture");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { takePhotoIntent });
startActivityForResult(chooserIntent, selectPic);
and at onActivityResult() I do:
Bitmap bitmapSelectedImage = null;
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
String filePath = cursor.getString(cursor.getColumnIndex(filePathColumn[0]));
cursor.close();
bitmapSelectedImage = BitmapFactory.decodeFile(filePath); // Here is where do I get error.
I get error on bitmapSelectedImage = BitmapFactory.decodeFile(filePath); line.
I have looked a lot websites/topics for it but no one could helped.
Any suggestions?
your memory allocation heap size is something very limited.
trying loading high resolution image from file to the heap can easily cause out of memory error.
assuming that the camera app really taking a very high resolution (almost sure that is the case), you should load to memory only scaled version of the bitmap in the size required for displaying.
the document you already been suggested to see - http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
provides full functionall methods to do exactly that.
1) first step is calculating (without loading to memory) the required scale.
that's the calculateInSampleSize method.
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float)height / (float)reqHeight);
final int widthRatio = Math.round((float)width / (float)reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions smaller than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
2) second step is the full method using step 1:
public static Bitmap getSampleBitmapFromFile(String bitmapFilePath, int reqWidth, int reqHeight) {
// calculating image size
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(new File(bitmapFilePath)), null, options);
int scale = calculateInSampleSize(options, reqWidth, reqHeight);
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(new File(bitmapFilePath)), null, o2);
}
reqHeight and reqWith are the hight and width in pixels of the image view that displaying the image.
so let's say your image view is 100x100 pixels, all you need to do is:
bitmapSelectedImage = getSampleBitmapFromFile(filePath, 100, 100);
If bitmap sizes are very big or inefficently handled then This problems occurs. To decode bitmap efficiently you can check these tips in android developers site.
Displaying Bitmaps Efficiently
Do not use strong references for bitmaps. Use it as below. Always Use weakreferences so that system can gc the object and reduce the memory leaks
WeakReference<Bitmap> bitmapSelectedImage ;
You need to scale down your image.
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html.
Use appropriate Bitmap.decode method and scale down the image.
Bitmap.decode
Example :
Call the method with the required parameters.
public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//The new size we want to scale to
final int REQUIRED_WIDTH=WIDTH;
final int REQUIRED_HIGHT=HIGHT;
//Find the correct scale value. It should be the power of 2.
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
scale*=2;
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
This code worked for me :try this
Bitmap ThumbImage = ThumbnailUtils.extractThumbnail(bitmap, 100, 100);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Android: Strange out of memory issue while loading an image to a Bitmap object
OutOfMemoryError: bitmap size exceeds VM budget :- Android
I have an application where users can take pictures or use one already existing in the gallery, and attach to a news, after saving the news in the database (I am only saving the image path content :/ / ...), I display all news in a ListView with an image title and date. to display the images in the adapter I'm using the following:
...
image.setImageURI(null);
System.gc();
image.setImageURI(Uri.parse(noticia.getIMAGEM()));
...
however even using the System.gc (); each new image that is loaded'm getting
12-12 14:59:37.239: E / AndroidRuntime (4997):
java.lang.OutOfMemoryError: bitmap size exceeds performer VM budget
also already tried using
image.setImageURI(null);
System.gc();
in onResume(), onPause(), onDestroy(), but nothing worked.
also read this post: [link][1]
if(!((BitmapDrawable)image.getDrawable()).getBitmap().isRecycled()){
((BitmapDrawable)image.getDrawable()).getBitmap().recycle();
}
Bitmap thumbnail = null;
try {
thumbnail = MediaStore.Images.Media.getBitmap(context.getContentResolver(), Uri.parse(img));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
image.setImageBitmap(thumbnail);
but then I get the following error:
12-12 15:28:42.879: E/AndroidRuntime(5296):
java.lang.RuntimeException: Canvas: trying to use a recycled bitmap
android.graphics.Bitmap#40756520
and besides when my list view to scroll up and down it keeps crashing, I believe that it is requesting the images ..
I do not know what else to do, any tips?
EDIT:
I found another post in the same solution to this problem worked perfectly, however I believe it would need a cache for the images because when scrolling the list up or down the one she fought, and this is very bad for the User Experience . Any idea to solve?
the following code:
in adapter:
...
String imagePath = getPath(Uri.parse(img));
image.setImageBitmap(decodeSampledBitmapFromResource(imagePath, 85, 85));
...
methods:
public String getPath(Uri uri)
{
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 2;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(String resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(resId, options);
}
It sounds like you want to ge thumbnail from local gallery. There is a better solution directly provided by the SDK :
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap thumbnail = Thumbnails.getThumbnail(context.getContentResolver(), /*ID of the local item*/, Thumbnails.MINI_KIND, options);
// Calculate inSampleSize
options.inSampleSize = UIUtils.calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
thumbnail = Thumbnails.getThumbnail(context.getContentResolver(), /*ID of the local item*/, Thumbnails.MINI_KIND, options);