Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 使用 ExifInterface 讀取拍照後的圖片屬性

編輯:關於 Android 程式設計

拍照後的 JPEG 檔其實夾帶了大量拍攝資訊:解析度、方向、拍攝時間、機型、GPS 座標等等。Android 提供了 ExifInterface 來讀取這些標籤,用法相當直接。

基本讀取

ExifInterface exif = new ExifInterface(file.getPath());
String widthStr  = exif.getAttribute(ExifInterface.TAG_IMAGE_WIDTH);
String heightStr = exif.getAttribute(ExifInterface.TAG_IMAGE_LENGTH);

若確定標籤一定是數值,也可以直接用 getAttributeInt(tag, 預設值);若遇到焦距這類分數格式的欄位,則該用 getAttributeDouble(),它會自動把 "num/denom" 換算成小數。

常用標籤一覽

  • TAG_ORIENTATION:拍攝方向,決定顯示時要不要旋轉,是處理「照片躺倒」問題的關鍵。
  • TAG_IMAGE_WIDTH / TAG_IMAGE_LENGTH:影像寬與高。
  • TAG_DATETIME:拍攝時間,格式為 "yyyy:MM:dd HH:mm:ss"。
  • TAG_MAKE / TAG_MODEL:製造商與機型。
  • TAG_FLASH、TAG_FOCAL_LENGTH、TAG_WHITE_BALANCE:閃光燈狀態、焦距、白平衡。
  • TAG_GPS_LATITUDE / LONGITUDE 及對應的 REF:經緯度與南北/東西方位。

官方實作參考

以下為 android.media.ExifInterface 的源碼,可作為理解標籤結構與 API 設計的依據:

package android.media;

import java.io.IOException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

/**
 * 用於讀寫 JPEG 檔中 Exif 標籤的類別。
 */
public class ExifInterface {

    /** Type is int. */
    public static final String TAG_ORIENTATION = "Orientation";
    /** Type is String. */
    public static final String TAG_DATETIME = "DateTime";
    /** Type is String. */
    public static final String TAG_MAKE = "Make";
    /** Type is String. */
    public static final String TAG_MODEL = "Model";
    /** Type is int. */
    public static final String TAG_FLASH = "Flash";
    /** Type is int. */
    public static final String TAG_IMAGE_WIDTH = "ImageWidth";
    /** Type is int. */
    public static final String TAG_IMAGE_LENGTH = "ImageLength";
    /** String. 格式為 "num1/denom1,num2/denom2,num3/denom3"。 */
    public static final String TAG_GPS_LATITUDE = "GPSLatitude";
    public static final String TAG_GPS_LONGITUDE = "GPSLongitude";
    public static final String TAG_GPS_LATITUDE_REF = "GPSLatitudeRef";
    public static final String TAG_GPS_LONGITUDE_REF = "GPSLongitudeRef";
    public static final String TAG_GPS_TIMESTAMP = "GPSTimeStamp";
    public static final String TAG_GPS_DATESTAMP = "GPSDateStamp";
    /** Type is int. */
    public static final String TAG_WHITE_BALANCE = "WhiteBalance";
    /** Type is rational. */
    public static final String TAG_FOCAL_LENGTH = "FocalLength";
    public static final String TAG_GPS_PROCESSING_METHOD = "GPSProcessingMethod";

    // 方向標籤的常數
    public static final int ORIENTATION_UNDEFINED = 0;
    public static final int ORIENTATION_NORMAL = 1;
    public static final int ORIENTATION_FLIP_HORIZONTAL = 2;
    public static final int ORIENTATION_ROTATE_180 = 3;
    public static final int ORIENTATION_FLIP_VERTICAL = 4;
    public static final int ORIENTATION_TRANSPOSE = 5;
    public static final int ORIENTATION_ROTATE_90 = 6;
    public static final int ORIENTATION_TRANSVERSE = 7;
    public static final int ORIENTATION_ROTATE_270 = 8;

    // 白平衡常數
    public static final int WHITEBALANCE_AUTO = 0;
    public static final int WHITEBALANCE_MANUAL = 1;

    private static SimpleDateFormat sFormatter;

    static {
        System.loadLibrary("exif");
        sFormatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
        sFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    }

    private String mFilename;
    private HashMap<String, String> mAttributes;
    private boolean mHasThumbnail;

    // 底層 jhead 使用靜態變數,同一時間只能有一個使用者,
    // 因此以 sLock 序列化所有存取。
    private static Object sLock = new Object();

    /** 從指定的 JPEG 檔讀取 Exif 標籤。 */
    public ExifInterface(String filename) throws IOException {
        mFilename = filename;
        loadAttributes();
    }

    /** 取得指定標籤的字串值,不存在時回傳 null。 */
    public String getAttribute(String tag) {
        return mAttributes.get(tag);
    }

    /** 取得整數值,標籤不存在或無法解析時回傳 defaultValue。 */
    public int getAttributeInt(String tag, int defaultValue) {
        String value = mAttributes.get(tag);
        if (value == null) return defaultValue;
        try {
            return Integer.valueOf(value);
        } catch (NumberFormatException ex) {
            return defaultValue;
        }
    }

    /** 取得 rational 型態標籤的 double 值。 */
    public double getAttributeDouble(String tag, double defaultValue) {
        String value = mAttributes.get(tag);
        if (value == null) return defaultValue;
        try {
            int index = value.indexOf("/");
            if (index == -1) return defaultValue;
            double denom = Double.parseDouble(value.substring(index + 1));
            if (denom == 0) return defaultValue;
            double num = Double.parseDouble(value.substring(0, index));
            return num / denom;
        } catch (NumberFormatException ex) {
            return defaultValue;
        }
    }

    /** 設定指定標籤的值。 */
    public void setAttribute(String tag, String value) {
        mAttributes.put(tag, value);
    }

    /** 從檔案載入所有屬性到 mAttributes。 */
    private void loadAttributes() throws IOException {
        // 原生層傳回的格式:
        // "attrCnt attr1=valueLen value1attr2=value2Len value2..."
        mAttributes = new HashMap<String, String>();
        String attrStr;
        synchronized (sLock) {
            attrStr = getAttributesNative(mFilename);
        }

        int ptr = attrStr.indexOf(' ');
        int count = Integer.parseInt(attrStr.substring(0, ptr));
        ++ptr;

        for (int i = 0; i < count; i++) {
            int equalPos = attrStr.indexOf('=', ptr);
            String attrName = attrStr.substring(ptr, equalPos);
            ptr = equalPos + 1;

            int lenPos = attrStr.indexOf(' ', ptr);
            int attrLen = Integer.parseInt(attrStr.substring(ptr, lenPos));
            ptr = lenPos + 1;

            String attrValue = attrStr.substring(ptr, ptr + attrLen);
            ptr += attrLen;

            if (attrName.equals("hasThumbnail")) {
                mHasThumbnail = attrValue.equalsIgnoreCase("true");
            } else {
                mAttributes.put(attrName, attrValue);
            }
        }
    }

    /**
     * 將標籤寫回 JPEG 檔。這個操作成本較高,因為需要複製整份影像資料、
     * 刪除舊檔再重新命名。建議先用 setAttribute() 一次設定全部,
     * 最後只呼叫一次本方法。
     */
    public void saveAttributes() throws IOException {
        StringBuilder sb = new StringBuilder();
        int size = mAttributes.size();
        if (mAttributes.containsKey("hasThumbnail")) {
            --size;
        }
        sb.append(size + " ");

        for (Map.Entry<String, String> iter : mAttributes.entrySet()) {
            String key = iter.getKey();
            if (key.equals("hasThumbnail")) {
                // 這不是真正的 Exif 標籤,不寫入
                continue;
            }
            String val = iter.getValue();
            sb.append(key + "=");
            sb.append(val.length() + " ");
            sb.append(val);
        }

        String s = sb.toString();
        synchronized (sLock) {
            saveAttributesNative(mFilename, s);
            commitChangesNative(mFilename);
        }
    }

    /** 是否含縮圖。 */
    public boolean hasThumbnail() {
        return mHasThumbnail;
    }

    /** 取得 JPEG 內的縮圖,若無則回傳 null。 */
    public byte[] getThumbnail() {
        synchronized (sLock) {
            return getThumbnailNative(mFilename);
        }
    }

    /** 將經緯度存入 float 陣列,回傳 false 表示標籤不足。 */
    public boolean getLatLong(float output[]) {
        String latValue = mAttributes.get(ExifInterface.TAG_GPS_LATITUDE);
        String latRef   = mAttributes.get(ExifInterface.TAG_GPS_LATITUDE_REF);
        String lngValue = mAttributes.get(ExifInterface.TAG_GPS_LONGITUDE);
        String lngRef   = mAttributes.get(ExifInterface.TAG_GPS_LONGITUDE_REF);

        if (latValue != null && latRef != null && lngValue != null && lngRef != null) {
            output[0] = convertRationalLatLonToFloat(latValue, latRef);
            output[1] = convertRationalLatLonToFloat(lngValue, lngRef);
            return true;
        }
        return false;
    }

    /** 回傳 1970 年以來的毫秒數,無資料時回傳 -1。 */
    public long getDateTime() {
        String dateTimeString = mAttributes.get(TAG_DATETIME);
        if (dateTimeString == null) return -1;
        ParsePosition pos = new ParsePosition(0);
        try {
            Date datetime = sFormatter.parse(dateTimeString, pos);
            return datetime == null ? -1 : datetime.getTime();
        } catch (IllegalArgumentException ex) {
            return -1;
        }
    }

    /** 回傳 GPS 時間的毫秒數,無資料時回傳 -1。 */
    public long getGpsDateTime() {
        String date = mAttributes.get(TAG_GPS_DATESTAMP);
        String time = mAttributes.get(TAG_GPS_TIMESTAMP);
        if (date == null || time == null) return -1;

        String dateTimeString = date + ' ' + time;
        ParsePosition pos = new ParsePosition(0);
        try {
            Date datetime = sFormatter.parse(dateTimeString, pos);
            return datetime == null ? -1 : datetime.getTime();
        } catch (IllegalArgumentException ex) {
            return -1;
        }
    }

    /** 將度分秒格式的字串轉為浮點度數。 */
    private static float convertRationalLatLonToFloat(String rationalString, String ref) {
        try {
            String[] parts = rationalString.split(",");
            String[] pair;

            pair = parts[0].split("/");
            int degrees = (int) (Float.parseFloat(pair[0].trim())
                               / Float.parseFloat(pair[1].trim()));

            pair = parts[1].split("/");
            int minutes = (int) (Float.parseFloat(pair[0].trim())
                               / Float.parseFloat(pair[1].trim()));

            pair = parts[2].split("/");
            float seconds = Float.parseFloat(pair[0].trim())
                          / Float.parseFloat(pair[1].trim());

            float result = degrees + (minutes / 60F) + (seconds / (60F * 60F));
            if (ref.equals("S") || ref.equals("W")) {
                return -result;
            }
            return result;
        } catch (RuntimeException ex) {
            return 0f;
        }
    }

    private native boolean appendThumbnailNative(String fileName, String thumbnailFileName);
    private native void saveAttributesNative(String fileName, String compressedAttributes);
    private native String getAttributesNative(String fileName);
    private native void commitChangesNative(String fileName);
    private native byte[] getThumbnailNative(String fileName);
}

實務提醒

讀取 Exif 之前請先確認檔案存在且可讀,丟出 IOException 要處理。另外,若要讀取 GPS 或寫入標籤,别忘了在清單中補上相應權限;Android 10 以上對外部儲存的存取限制更嚴格,建議改用 MediaStore 或 App 專屬目錄存放照片。最後記得:ExifInterface 只支援 JPEG,PNG 與 WebP 的支援程度依版本而異。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved