Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 2.2 Camera 應用把 GPS 資訊寫進 JPEG 檔的兩種做法

問題背景

Android 2.2 原生的 Camera 應用程式並不會把 GPS 資訊寫入 JPEG 檔。想補上這個功能,大致有兩條路。

做法一:改底層 Camera 驅動。拍照時通常由硬體進行 JPEG 編碼,因此要修改 JPEG 編碼器,讓它在編碼時把 GPS 資訊寫進檔案頭的 EXIF 區塊。這種方式最徹底、效能也最好,但適合有手機/平台驅動開發能力的人。

做法二:改 Camera 應用程式。應用層本身不支援,但 Android 提供了現成的 ExifInterface 類別可以讀寫 EXIF。代價是每寫一次 GPS,就得把原 JPEG 讀出來、改完 EXIF 標頭再寫回去,多了一次 I/O。

找到插入點:addImage()

相關檔案在 packages/apps/Camera/src/com/android/camera/ImageManager.java,其中的 addImage() 負責把拍好的照片寫入媒體庫:

public static Uri addImage(ContentResolver cr, String title, long dateTaken,
        Location location, String directory, String filename,
        Bitmap source, byte[] jpegData, int[] degree) {
    ...
    String filePath = directory + "/" + filename;
    ...
    if (location != null) {
        values.put(Images.Media.LATITUDE,  location.getLatitude());
        values.put(Images.Media.LONGITUDE, location.getLongitude());
    }
    return cr.insert(STORAGE_URI, values);
}

這裡的判斷很關鍵:當 location 不為 null,代表「儲存位置」功能已開啟,而且 GPS 已開啟且定位正常。這個條件成立的瞬間,就是寫入 EXIF 的最佳時機。

加入 ExifInterface 後的樣子

public static Uri addImage(ContentResolver cr, String title, long dateTaken,
        Location location, String directory, String filename,
        Bitmap source, byte[] jpegData, int[] degree) {
    ...
    String filePath = directory + "/" + filename;
    ...

    if (location != null) {
        values.put(Images.Media.LATITUDE,  location.getLatitude());
        values.put(Images.Media.LONGITUDE, location.getLongitude());

        ExifInterface exif = null;
        try {
            exif = new ExifInterface(filePath);
        } catch (IOException ex) {
            Log.e(TAG, "cannot read exif", ex);
        }

        exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE,
                Double.toString(location.getLatitude()));
        exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE,
                Double.toString(location.getLongitude()));

        try {
            if (exif != null)
                exif.saveAttributes();
        } catch (IOException ex) {
            Log.e(TAG, "Fail to exif.saveAttributes().");
        }
    }
    return cr.insert(STORAGE_URI, values);
}

流程是:以檔案路徑建立 ExifInterface → 用 setAttribute 寫入經緯度 → 呼叫 saveAttributes() 落盤,全程包在 try/catch 裡避免 I/O 例外中斷拍照流程。

實作提醒

這個範例有兩個可以再加強的地方:其一,new ExifInterface(filePath) 失敗時 exif 仍為 null,後續直接呼叫 setAttribute 會拋出 NullPointerException,應該把寫入也包進同一個防護;其二,EXIF 的 GPS 標籤格式有分度分秒與十進位表示,若要與其他看图軟體完全相容,建議改用 TAG_GPS_LATITUDE_REF、經度參考方向等完整標籤組合,並依規範格式化數值。

Copyright © Linux教程網 All Rights Reserved