利用JPEG文件中的EXIF信息调整照片方向

利用JPEG文件中的EXIF信息调整照片方向

问题起源:竖屏应用的预览图像和拍摄的照片均旋转了90度

这个问题的原因是,在Android系统中定义了相机传感器方向,这个方向默认为:当你面对屏幕时,横置手机,如果摄像头靠近上方,那么此时即默认方向。当竖立手机,且前置、后置摄像头都在上方时,前置摄像头的旋转角度为270,后置旋转角度为90。

怎样应对

该问题影响两个方面:

  • 相机的预览画面方向
  • 拍摄的照片存储方向

对于预览方向,可以通过 CameraInfo.orientation 参数来获得前文所说的旋转角度,再通过 Camera.setDisplayOrientation(int degree) 方法来设置预览角度即可;

而对于存储方向,情况就复杂一些。设置旋转角度的方法如下:

Camera.Parameters parameters;
parameters.setRotation(rotation);
mCamera.setParameters(parameters); 

但在这个操作之后,不同手机的处理是不同的。有些手机会直接将照片旋转指定的角度,但照片文件中的 EXIF信息中的 orientation 不变(即仍为0);有些手机会只将 EXIF 信息中的 orientation 保存为相应的角度,但不操作照片方向。

因此,我们需要读取照片(JPEG 文件)中的 EXIF 信息,根据其 orientation 来旋转 Bitmap。在 Android 中,有 ExifInterface 类来获取文件的 EXIF 信息,但该接口只支持用文件来实例化,如下:

    ExifInterface exif = null;
    try {
        exif = new ExifInterface(filepath);
    } catch (IOException ex) {
        Log.e(TAG, "cannot read exif", ex);
    }
    if (exif != null) {
        int orientation = exif.getAttributeInt(
            ExifInterface.TAG_ORIENTATION, -1);
    }

而相机的 takePicture(shutter, raw, jpeg) 方法回调的 PictureCallback 中,onPictureTaken(final byte[] data, Camera camera) 方法得到的是相片的 byte[] 形式,是否能直接从中读取我们需要的 orientation 信息呢?

其实,在 Android 4.1.1 的 Camera 源码中,就已经实现了一个非常简洁的方法,如下:

    // Returns the degrees in clockwise. Values are 0, 90, 180, or 270.
    public static int getOrientation(byte[] jpeg) {
        if (jpeg == null) {
            return 0;
        }

        int offset = 0;
        int length = 0;

        // ISO/IEC 10918-1:1993(E)
        while (offset + 3 < jpeg.length && (jpeg[offset++] & 0xFF) == 0xFF) {
            int marker = jpeg[offset] & 0xFF;

            // Check if the marker is a padding.
            if (marker == 0xFF) {
                continue;
            }
            offset++;

            // Check if the marker is SOI or TEM.
            if (marker == 0xD8 || marker == 0x01) {
                continue;
            }
            // Check if the marker is EOI or SOS.
            if (marker == 0xD9 || marker == 0xDA) {
                break;
            }

            // Get the length and check if it is reasonable.
            length = pack(jpeg, offset, 2, false);
            if (length < 2 || offset + length > jpeg.length) {
                Log.e(TAG, "Invalid length");
                return 0;
            }

            // Break if the marker is EXIF in APP1.
            if (marker == 0xE1 && length >= 8 &&
                    pack(jpeg, offset + 2, 4, false) == 0x45786966 &&
                    pack(jpeg, offset + 6, 2, false) == 0) {
                offset += 8;
                length -= 8;
                break;
            }

            // Skip other markers.
            offset += length;
            length = 0;
        }

        // JEITA CP-3451 Exif Version 2.2
        if (length > 8) {
            // Identify the byte order.
            int tag = pack(jpeg, offset, 4, false);
            if (tag != 0x49492A00 && tag != 0x4D4D002A) {
                Log.e(TAG, "Invalid byte order");
                return 0;
            }
            boolean littleEndian = (tag == 0x49492A00);

            // Get the offset and check if it is reasonable.
            int count = pack(jpeg, offset + 4, 4, littleEndian) + 2;
            if (count < 10 || count > length) {
                Log.e(TAG, "Invalid offset");
                return 0;
            }
            offset += count;
            length -= count;

            // Get the count and go through all the elements.
            count = pack(jpeg, offset - 2, 2, littleEndian);
            while (count-- > 0 && length >= 12) {
                // Get the tag and check if it is orientation.
                tag = pack(jpeg, offset, 2, littleEndian);
                if (tag == 0x0112) {
                    // We do not really care about type and count, do we?
                    int orientation = pack(jpeg, offset + 8, 2, littleEndian);
                    switch (orientation) {
                        case 1:
                            return 0;
                        case 3:
                            return 180;
                        case 6:
                            return 90;
                        case 8:
                            return 270;
                    }
                    Log.i(TAG, "Unsupported orientation");
                    return 0;
                }
                offset += 12;
                length -= 12;
            }
        }

        Log.i(TAG, "Orientation not found");
        return 0;
    }

    private static int pack(byte[] bytes, int offset, int length,
            boolean littleEndian) {
        int step = 1;
        if (littleEndian) {
            offset += length - 1;
            step = -1;
        }

        int value = 0;
        while (length-- > 0) {
            value = (value << 8) | (bytes[offset] & 0xFF);
            offset += step;
        }
        return value;
    }

取得照片的方向信息之后,只要再通过 Bitmap 操作即可得到正确方向的图片了:

public static Bitmap rotateBitmap(Bitmap bm, float degree) {

    Matrix matrix = new Matrix();
    matrix.reset();
    matrix.setRotate(degree);
    Bitmap temp = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
    return temp;
}

关于 EXIF 信息的格式

JPEG 文件中的 EXIF 信息一般包括图像、相机和缩略图等信息。EXIF 文件格式基本上与 JPEG 文件格式一致,因此加入 EXIF 信息并不影响 JPEG 文件的查看。

JPEG 文件中有一些形如 0xFF** 这样的数据,它们被称为“标志(Marker)”,它表示 JPEG 信息数据段。例如 0xFFD8 代表 SOI(Start of image), 0xFFD9 代表 EOI(End of image)。这两个标志是特例,因为它们之后不跟数据。而一般的标志格式如下:

0xFF+Marker Number(1 byte)+Data size(2 bytes)+Data(n bytes)

标志 0xFFE0~0xFFEF 被称为 "Application Marker",它们不是解码 JPEG 文件必须的,可以被用来存储配置信息等。EXIF 也是利用这个标志段来插入信息的,具体来说,是 APP1(0xFFE1) Marker。所有的 EXIF 信息都存储在该数据段。我们可以跟据具体的数据结构来解析出需要的信息,比如方向。详细的数据结构,请查看参考1的文章。

参考:

  1. https://www.media.mit.edu/pia/Research/deepview/exif.html

  2. http://stackoverflow.com/questions/5468098/reading-exif-data-from-byte-array-in-android

posted @ 2016-08-29 20:38  NoodleUtopia  阅读(5288)  评论(0编辑  收藏  举报