Android:如何在imageview上设置时检测从图库中选取的图像方向(纵向或横向)?

sar*_*i05 32 android android-gallery android-imageview

我正在从图库(相册)中选取的imageview上设置图像.如果摄取的图像具有横向,它显示完美,但如果在肖像模式(即图像被点击在纵向模式下),它会显示一个90度旋转图像的图像.现在我试图在设置imageview之前找出方向,但所有图像都给出相同的方向和相同的宽度 - 高度.这是我的代码:

Uri selectedImage = intent.getData();
if (selectedImage != null) {
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);

    int str = new ExifInterface(selectedImage.getPath()).getAttributeInt("Orientation", 1000);
    Toast.makeText(this, "value:" + str, Toast.LENGTH_LONG).show();
    Toast.makeText(this, "width:" + bitmap.getWidth() + "height:" + bitmap.getHeight(), Toast.LENGTH_LONG).show();
Run Code Online (Sandbox Code Playgroud)

肖像模式 景观模式

Dee*_*pak 53

使用ExifInterface用于旋转图像.使用此方法获取正确的值以从相机旋转捕获的图像.

public int getCameraPhotoOrientation(Context context, Uri imageUri, String imagePath){
    int rotate = 0;
    try {
        context.getContentResolver().notifyChange(imageUri, null);
        File imageFile = new File(imagePath);

        ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

        switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_270:
            rotate = 270;
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            rotate = 180;
            break;
        case ExifInterface.ORIENTATION_ROTATE_90:
            rotate = 90;
            break;
        }

        Log.i("RotateImage", "Exif orientation: " + orientation);
        Log.i("RotateImage", "Rotate value: " + rotate);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return rotate;
}
Run Code Online (Sandbox Code Playgroud)

并将此代码放在Activity结果方法中并获取旋转图像的值...

String selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};

Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();

int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();

int rotateImage = getCameraPhotoOrientation(MyActivity.this, selectedImage, filePath);
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助..

  • @Deepak为什么我必须调用`context.getContentResolver().notifyChange(imageUri,null)`? (9认同)
  • exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_NORMAL); 对于任何方向图像,始终返回值0. (2认同)

sar*_*i05 5

这对我也有用:

String[] orientationColumn = {MediaStore.Images.Media.ORIENTATION};
Cursor cur = getContentResolver().query(imageUri, orientationColumn, null, null, null);
int orientation = -1;
if (cur != null && cur.moveToFirst()) {
    orientation = cur.getInt(cur.getColumnIndex(orientationColumn[0]));
}
Matrix matrix = new Matrix();
matrix.postRotate(orientation);
Run Code Online (Sandbox Code Playgroud)