android - 如何获取从默认图像库中选择的图像的正确方向

标签 android image android-intent android-camera image-gallery

我已经浏览了一些链接以获取从默认图片库中选择的图片的正确图片方向,以便在所有设备中作为标准工作,exif 标记始终返回 0。

EXIF orientation tag value always 0 for image taken with portrait camera app android

Exif orientation tag returns 0

Exif data TAG_ORIENTATION always 0

http://mobisocial.stanford.edu/news/2011/08/rotating-images-in-android/

如何获得适用于所有设备的精确解决方案?

最佳答案

如果图像(照片)是由您制作的程序拍摄的,则必须将 Parameters.setRotation 设置为正确的旋转值。

这取决于相机驱动,在保存之前旋转图像或将旋转值保存到 exif TAG_ORIENTATION。

因此,如果 TAG_ORIENTATION 为空或零,则图像方向正确,否则您必须根据 TAG_ORIENTATION 中的值旋转图像。

代码

从 EXIF 获取方向:

ExifInterface exif = null;
try {
    exif = new ExifInterface(path);
} catch (IOException e) {
    e.printStackTrace();
}  
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 
                                       ExifInterface.ORIENTATION_UNDEFINED);

旋转位图:

Bitmap bmRotated = rotateBitmap(bitmap, orientation);  

位图旋转方法:

public static Bitmap rotateBitmap(Bitmap bitmap, int orientation) {

    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.setRotate(180);
            break;
        case ExifInterface.ORIENTATION_FLIP_VERTICAL:
            matrix.setRotate(180);
            matrix.postScale(-1, 1);
            break;
        case ExifInterface.ORIENTATION_TRANSPOSE:
            matrix.setRotate(90);
            matrix.postScale(-1, 1);
            break;
       case ExifInterface.ORIENTATION_ROTATE_90:
           matrix.setRotate(90);
           break;
       case ExifInterface.ORIENTATION_TRANSVERSE:
           matrix.setRotate(-90);
           matrix.postScale(-1, 1);
           break;
       case ExifInterface.ORIENTATION_ROTATE_270:
           matrix.setRotate(-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;
    }
}

关于android - 如何获取从默认图像库中选择的图像的正确方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20478765/

相关文章:

可以在运行时从插件接收自定义逻辑的 Android Activity

android 使布局在软键盘打开时可滚动,但不向上移动

java.lang.IllegalStateException : TimerTask is scheduled already 错误

python - 在 python opencv 中添加像素?

ios - 从 ios 上的图像中获取文本(图像处理)

android - 如何将我的应用程序添加到 Android 默认拨号器选择中?

java - 安卓工作室 : how to pass customed objects in intent

android - 在 IntelliJ 9.0 Maia Public Beta 下构建 Android 应用时出现 "Resource not found"

android - 如何为 firebase 创建自定义用户属性?

php - 复制后损坏的图像