My app is supposed to get a picture from the gallery and display it in an ImageView
, I am getting what I want with all the images EXCEPT the ones I took with my back camera, they show up in the gallery for me to pick and even return the path, but all I get is blankness in my ImageView
.
This is the code:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(intent, SELECT_PICTURE);
my onActivityResult code is this:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_PICTURE && resultCode == RESULT_OK && null != data) {
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
ImageView iv = (ImageView) getView().findViewById(R.id.iv_foto);
iv.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It works with images taken with my front camera.
I haven't tried the app on another phone but if this happens in mine, chances are someone else will have the same problem.
The issue is with the size of the image.
I've successfully fixed the same issue with scaling the Bitmap
before displaying in the ImageView
Bitmap sourceBitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri);
try {
Bitmap sourceBitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri);
float rotationInDegrees = 0;
Cursor cursor = contentResolver.query(uri, new String[]{MediaStore.Images.ImageColumns.ORIENTATION},
null,
null,
null);
if (cursor != null && cursor.moveToFirst()) {
int col = cursor.getColumnIndex(MediaStore.Images.ImageColumns.ORIENTATION);
if (col != -1)
rotationInDegrees = cursor.getInt(col);
cursor.close();
}
Matrix matrix = new Matrix();
matrix.preRotate(rotationInDegrees);
int width, height;
double aspectRatio;
aspectRatio = (double) sourceBitmap.getWidth() / sourceBitmap.getHeight();
if (sourceBitmap.getHeight() > sourceBitmap.getWidth()) {
height = MAX_IMAGE_DIMENSION;
width = (int) (height * aspectRatio);
} else {
width = MAX_IMAGE_DIMENSION;
height = (int) (width / aspectRatio);
}
sourceBitmap = Bitmap.createScaledBitmap(sourceBitmap, width, height, false);
return Bitmap.createBitmap(sourceBitmap, 0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight(), matrix, false);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("ImageHelper@getImageFromUri: IOException");
}