Android的:如何检测图像方向(纵向或横向)从图库挑,而在一个ImageView的设置?而在、纵向、横向、图像

2023-09-12 23:56:34 作者:繁华落尽〆空城伤

我设置的图像从画廊(相册)在ImageView的回升。如果摄取的图像具有横向,它显示完美,但如果在肖像模式(即该图像被点击以纵向模式)它显示具有90度旋转的图像的图像。现在我想找到了方向之前在ImageView的设置,但所有的图像都给予相同的方向和相同的宽度,高度。这是我的code:

I am setting an image on the imageview picked from the gallery(camera album). If the picked image has landscape orientation, it displays perfectly but if the image in in portrait mode(i.e the image was clicked in portrait mode) it is displaying the image with a 90 degree rotation. Now I am trying to find out the orientation just before setting on imageview, but all the images are giving same orientation and same width-height. Here is my code :

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();

推荐答案

使用 ExifInterface 用于旋转图像。使用此方法获得正确的值是旋转拍摄的图像从相机。

Use ExifInterface for rotate image. Use this method for get correct value to be rotate captured image from camera.

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;
}

和把这个code。在活动结果的方法,并获得价值旋转图像...

And put this code in Activity result method and get value to rotate image...

            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);

希望这有助于..

Hope this helps..