Я работаю над Android-проектом, в котором пользователь может загрузить изображение как изображение профиля. Все работало нормально до определенного момента (в конце концов, до обновления Samsung). С тех пор изображения на устройствах Samsung Galaxy (возможно, также на других), но на моем HTC One XL он работает нормально, на моем планшете Lenovo Yoga и на Sony (точно не знаю, на каком) тоже. Но на Galaxy S6 и S5 он поворачивает изображение. Идея состоит в том, что Изображение устанавливается в "нормальном" ракурсе, как это воспринимал Пользователь. Это означает, что он должен занимать только квадрат, но, конечно, чтобы он был в вертикальном положении. В устройствах Samsung голова повернута на 90 градусов против часовой стрелки. Код отлично работает на других устройствах. Есть у кого-то такая же проблема? Любая идея? Вот код
// After image taken
public void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
// data returned
if (resultCode != FragmentActivity.RESULT_CANCELED) {
if (requestCode == RESULT_LOAD_IMAGE && resultCode == getActivity().RESULT_OK){
// Set profile image from gallery
try {
Uri selectedImage = data.getData();
photo = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImage);
photo = MainUtils.rotateBitmap(photo, data, getActivity());
photo = MainUtils.resizeBitmapIfNeeded(photo, 800, 800);
byte[] byteArray;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 90, stream);
byteArray = stream.toByteArray();
// Save image to parse as ParseFile and connect to the ParseUser (redacted)
}
Методы MainUtils:
public static Bitmap resizeBitmapIfNeeded(Bitmap image, int maxWidth, int maxHeight) {
if (maxHeight > 0 && maxWidth > 0) {
int wid = image.getWidth();
int hei = image.getHeight();
MainUtils.log(" resizeBitmapIfNeeded, size is " + wid + " X " + hei);
if (wid > maxWidth || hei > maxHeight) {
int width = image.getWidth();
int height = image.getHeight();
float ratioBitmap = (float) width / (float) height;
float ratioMax = (float) maxWidth / (float) maxHeight;
int finalWidth = maxWidth;
int finalHeight = maxHeight;
if (ratioMax > 1) {
finalWidth = (int) ((float) maxHeight * ratioBitmap);
} else {
finalHeight = (int) ((float) maxWidth / ratioBitmap);
}
image = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true);
wid = image.getWidth();
hei = image.getHeight();
MainUtils.log(" resizeBitmapIfNeeded, resized size is " + wid + " X " + hei);
return image;
} else {
return image;
}
} else {
return image;
}
}
public static Bitmap rotateBitmap(Bitmap bitmap, Intent data, Context context) {
int orientation = 0;
try {
Uri selectedImage = data.getData();
ExifInterface exif;
exif = new ExifInterface(MainUtils.getRealPathFromUri(context, selectedImage));
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
MainUtils.log("Orientation is " + orientation);
} catch (IOException excep) {
MainUtils.log("Rotate " + excep.getMessage());
}
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
return bitmap;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
matrix.setScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.postRotate(180);
break;
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
matrix.postRotate(180);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_TRANSPOSE:
matrix.postRotate(90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.postRotate(90);
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
matrix.postRotate(-90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.postRotate(-90);
break;
default:
return bitmap;
}
try {
Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
return bmRotated;
}
catch (OutOfMemoryError e) {
e.printStackTrace();
return null;
}
}
public static Bitmap rotateBitmapFromFile(String picturePath) {
int orientation = 0;
Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
try {
ExifInterface exif = new ExifInterface(picturePath);
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
MainUtils.log("Orientation is " + orientation);
} catch (IOException excep) {
MainUtils.log("Rotate " + excep.getMessage());
}
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
return bitmap;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
matrix.setScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.postRotate(180);
break;
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
matrix.postRotate(180);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_TRANSPOSE:
matrix.postRotate(90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.postRotate(90);
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
matrix.postRotate(-90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.postRotate(-90);
break;
default:
return bitmap;
}
try {
Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
return bmRotated;
}
catch (OutOfMemoryError e) {
e.printStackTrace();
return null;
}
}
Галерея намерений
Intent intent = new Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
galleryRequest);
mCurrentPhotoPath
. - person greenapps   schedule 26.10.2016getRealPathFromUri()
. Проклятье пользоваться такими функциями. Они могут вернутьnull
. Вы могли бы по крайней мере адаптировать свой код таким образом, чтобы он проверял значение null перед использованием. Затем покажите тост. - person greenapps   schedule 27.10.2016exif = new Exifinterface(null)
исключение. Если это разрешено, ориентация всегда будет равна 0. - person greenapps   schedule 27.10.2016