压缩后保持图像方向

时间:2012-12-17 13:41:57

标签: android android-image

这是我的代码

        //
        // reading an image captured using phone camera. Orientation of this
        // image is always return value 6 (ORIENTATION_ROTATE_90) no matter if
        // it is captured in landscape or portrait mode
        //
        Bitmap bmp = BitmapFactory.decodeFile(imagePath.getAbsolutePath());

        //
        // save as : I am compressing this image and writing it back. Orientation 
        //of this image always returns value 0 (ORIENTATION_UNDEFINED)
        imagePath = new File(imagePath.getAbsolutePath().replace(".jpg", "_1.jpg"));



        FileOutputStream fos0 = new FileOutputStream(imagePath);
        boolean b = bmp.compress(CompressFormat.JPEG, 10, fos0);
        fos0.flush();
        fos0.close();
        fos0 = null;

压缩和保存后,虽然ExifInterface返回0(ORIENTATION_UNDEFINED),但图像会旋转90度。任何指针,我如何保留源图像的方向;在这种情况下,它是6(或ORIENTATION_ROTATE_90)。

感谢。

2 个答案:

答案 0 :(得分:5)

经过对stackoverflow的更多搜索后,发现有人已经解决了这个问题here与解决方案的完美结合(我已经投了赞)。

答案 1 :(得分:0)

以下代码将按其ORIENTATION返回图像角度。

public static float rotationForImage(Context context, Uri uri) {
        if (uri.getScheme().equals("content")) {
        String[] projection = { Images.ImageColumns.ORIENTATION };
        Cursor c = context.getContentResolver().query(
                uri, projection, null, null, null);
        if (c.moveToFirst()) {
            return c.getInt(0);
        }
    } else if (uri.getScheme().equals("file")) {
        try {
            ExifInterface exif = new ExifInterface(uri.getPath());
            int rotation = (int)exifOrientationToDegrees(
                    exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                            ExifInterface.ORIENTATION_NORMAL));
            return rotation;
        } catch (IOException e) {
            Log.e(TAG, "Error checking exif", e);
        }
    }
        return 0f;
    }

    private static float exifOrientationToDegrees(int exifOrientation) {
    if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
        return 90;
    } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
        return 180;
    } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
        return 270;
    }
    return 0;
}
}