1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.camera;
18
19import android.util.Log;
20
21import com.android.gallery3d.exif.ExifInvalidFormatException;
22import com.android.gallery3d.exif.ExifParser;
23import com.android.gallery3d.exif.ExifTag;
24
25import java.io.ByteArrayInputStream;
26import java.io.IOException;
27import java.io.InputStream;
28
29public class Exif {
30    private static final String TAG = "CameraExif";
31
32    // Returns the degrees in clockwise. Values are 0, 90, 180, or 270.
33    public static int getOrientation(byte[] jpeg) {
34        if (jpeg == null) return 0;
35
36        InputStream is = new ByteArrayInputStream(jpeg);
37
38        try {
39            ExifParser parser = ExifParser.parse(is, ExifParser.OPTION_IFD_0);
40            int event = parser.next();
41            while(event != ExifParser.EVENT_END) {
42                if (event == ExifParser.EVENT_NEW_TAG) {
43                    ExifTag tag = parser.getTag();
44                    if (tag.getTagId() == ExifTag.TAG_ORIENTATION &&
45                            tag.hasValue()) {
46                        int orient = (int) tag.getValueAt(0);
47                        switch (orient) {
48                            case ExifTag.Orientation.TOP_LEFT:
49                                return 0;
50                            case ExifTag.Orientation.BOTTOM_LEFT:
51                                return 180;
52                            case ExifTag.Orientation.RIGHT_TOP:
53                                return 90;
54                            case ExifTag.Orientation.RIGHT_BOTTOM:
55                                return 270;
56                            default:
57                                Log.i(TAG, "Unsupported orientation");
58                                return 0;
59                        }
60                    }
61                }
62                event = parser.next();
63            }
64            Log.i(TAG, "Orientation not found");
65            return 0;
66        } catch (IOException e) {
67            Log.w(TAG, "Failed to read EXIF orientation", e);
68            return 0;
69        } catch (ExifInvalidFormatException e) {
70            Log.w(TAG, "Failed to read EXIF orientation", e);
71            return 0;
72        }
73    }
74}
75