4

我正在从我的人像相机应用程序拍照并发送到服务器。在发送之前,我需要在必要时旋转图像。所以我将图像保存在 sdcard 中并尝试获取 Exif 或 Cursor。我经历了大部分与此相关的帖子。但对我没有任何作用。这是代码..

  1. Exif接口

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

    此处任何图像的方向始终为 0

  2. 光标

    int orientation = 0;
    final String[] projection = new String[] { MediaStore.Images.Media.ORIENTATION };
    final Cursor cursor = getApplicationContext()
                    .getContentResolver().query(uri, projection, null,
                            null, null); 
    if (cursor != null) {
    final int orientationColumnIndex = cursor.getColumnIndex(MediaStore.Images.Media.ORIENTATION);
    if (cursor.moveToFirst()) {
       orientation = cursor.isNull(orientationColumnIndex) ? 0 : cursor.getInt(orientationColumnIndex);
     }
    

    这里的图像旋转也是零。我怎样才能找到图像的确切旋转?任何帮助将不胜感激..

4

1 回答 1

0

请开始使用支持库中的 ExifInterface。它提供了一个支持 InputStream 的构造函数。从 Uri 获取路径是错误的。你需要这个库:在你的 build.gradle 中编译 'com.android.support:exifinterface:25.3.1'。代码

private float getOrientation (InputStream image, Uri photoURI) {
    //ExifInterface myExif = new ExifInterface(photoURI.getPath());

    float photoRotation = 0;
    boolean hasRotation = true;

    try {
        ExifInterface exif = new ExifInterface(image);
        int exifRotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_UNDEFINED);

        switch (exifRotation) {
            case ExifInterface.ORIENTATION_UNDEFINED: {
                hasRotation = false;
            }
            case ExifInterface.ORIENTATION_ROTATE_90: {
                photoRotation = 90.0f;
                break;
            }
            case ExifInterface.ORIENTATION_ROTATE_180: {
                photoRotation = 180.0f;
                break;
            }
            case ExifInterface.ORIENTATION_ROTATE_270: {
                photoRotation = 270.0f;
                break;
            }
        }
    } catch (IOException e) {
            Log.d("ODDREAMS", e.getMessage());
    }

    if (!hasRotation) {
        try {
                String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media.ORIENTATION};
                Cursor cursor = getActivity().getContentResolver().query(photoURI, columns, null, null, null);

                if (cursor == null) return 0;

                if (cursor.moveToFirst()) {
                    int orientationColumnIndex = cursor.getColumnIndex(columns[1]);
                    photoRotation = cursor.getInt(orientationColumnIndex);
                    Log.d("ODDREAMS", "CURSOR " + photoRotation);
                }
                cursor.close();
        }
        catch (Exception e) {}

    }

    return photoRotation;
}
于 2017-10-21T13:30:05.170 回答