How to save GPS coordinates in exif data on Android?

前端 未结 5 1428
借酒劲吻你
借酒劲吻你 2020-12-02 20:43

I am writing GPS coordinates to my JPEG image, and the coordinates are correct (as demonstrated by my logcat output) but it appears that it\'s being corrupted somehow. Readi

5条回答
  •  忘掉有多难
    2020-12-02 21:36

    Other answers delivered nice background info and even an example. This is not a direct answer to the question but I would like to add an even simpler example without the need to do any math. The Location class delivers a nice convert function:

    public String getLonGeoCoordinates(Location location) {
    
        if (location == null) return "0/1,0/1,0/1000";
        // You can adapt this to latitude very easily by passing location.getLatitude()
        String[] degMinSec = Location.convert(location.getLongitude(), Location.FORMAT_SECONDS).split(":");
        return degMinSec[0] + "/1," + degMinSec[1] + "/1," + degMinSec[2] + "/1000";
    }
    

    I stored the return value in my image and the tag is parsed fine. You can check your image and the geocoordinates inside here: http://regex.info/exif.cgi

    Edit

    @ratanas comment translated to code:

    public boolean storeGeoCoordsToImage(File imagePath, Location location) {
    
        // Avoid NullPointer
        if (imagePath == null || location == null) return false;
    
        // If we use Location.convert(), we do not have to worry about absolute values.
    
        try {
            // c&p and adapted from @Fabyen (sorry for being lazy)
            ExifInterface exif = new ExifInterface(imagePath.getAbsolutePath());
            exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE, getLatGeoCoordinates(location));
            exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, location.getLatitude() < 0 ? "S" : "N");
            exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, getLonGeoCoordinates(location));
            exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, location.getLongitude() < 0 ? "W" : "E");
            exif.saveAttributes();
        } catch (IOException e) {
            // do something
            return false;
        }
    
        // Data was likely written. For sure no NullPointer. 
        return true;
    }
    

    Here are some nice LatLong converter: latlong.net

提交回复
热议问题