I am scaling down an image taken by MediaStore.ACTION_IMAGE_CAPTURE
(Tried to follow all the better practices)
Scaling the image is done in two steps:
- Decode the perfect sample of the captured image to
Bitmap
. - Rotate and Scale the bitmap to fit into my device display size.
I don't really understand why sometimes image is perfectly displayed in the image view and sometimes its just blank! Any help is highly appreciated :-)
UPDATE: I am doing all the processing work in onActivityResult
. Not sure its the reason behind this weird behavior?
For better understanding of the problem i am sharing some of the key sections of code:
Bitmap Factory Options
BitmapFactory.Options options = new BitmapFactory.Options();
options.inDither = false;
options.inPurgeable = true;
options.inInputShareable = true;
options.inJustDecodeBounds = false;
options.inTempStorage = new byte[32 * 1024];
options.inSampleSize = calculateInSampleSize(imageHeight, imageWidth, screenHeight, screenWidth);
Sample Size calculation
private int calculateInSampleSize(int imageHeight, int imageWidth, int reqHeight, int reqWidth)
{
int inSampleSize = 1;
if (imageHeight > reqHeight || imageWidth > reqWidth) {
final int halfHeight = imageHeight / 2;
final int halfWidth = imageWidth / 2;
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
Decode and Re-sizing the Bitmap
image = BitmapFactory.decodeFile(fileName, options);
Matrix matrix = new Matrix();
float scaleFactor = Math.min(1.0f, Math.max(width / imageWidth, height / imageHeight));
matrix.postScale(scaleFactor, scaleFactor);
Bitmap tempImage = Bitmap.createBitmap(image, 0, 0, image.getWidth(), image.getHeight(), matrix, false);
if( image.isMutable() || (image.getHeight()!=tempImage.getHeight() || image.getWidth()!=tempImage.getWidth()) ) {
image.recycle();
}
imageView.setImageBitmap(tempImage);