How to write GPS coordinates to EXIF data on Andro

2019-08-06 04:11发布

问题:

I'm trying to write a geotagging app where the user selects an image form the photo gallery, and then that image gets the current GPS coordinates written to it through its EXIF file.

So far I am able to pull up the gallery, select an image, and find my current GPS coordinates, but I cannot write those coordinates to the EXIF file. Whenever I do select an image, I can view it, but no data is written to the EXIF file.

I have looked up several examples for how to write to EXIF, and my code looks correct (to me at least). Can anyone help me figure out why I am not writing any data?

Here's my code:

//place GPS cords into exif file
        try {
            ExifInterface exif = new ExifInterface("/sdcard/dcim/100MEDIA/IMAG0020.jpg");

            exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE, DMSconv(lat));
            exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE,DMSconv(lon));
            if (lat > 0) 
              exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, "N"); 
            else              
              exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, "S");
            if (lon > 0) 
              exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, "E");    
             else             
               exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, "W");
            exif.saveAttributes();

        } catch (IOException e) {
            e.printStackTrace();
        }

 //convert from decimal degrees to DMS
String DMSconv(double coord) {  
      coord = (coord > 0) ? coord : (-1)*coord;  // -105.9876543 -> 105.9876543
      String sOut = Integer.toString((int)coord) + "/1,";   // 105/1,
      coord = (coord % 1) * 60;         // .987654321 * 60 = 59.259258
      sOut = sOut + Integer.toString((int)coord) + "/1,";   // 105/1,59/1,
      coord = (coord % 1) * 6000;             // .259258 * 6000 = 1555
      sOut = sOut + Integer.toString((int)coord) + "/1000";   // 105/1,59/1,15555/1000
      return sOut;
    }

Thanks for the help!

Edit: At this time I was trying to hardcode the file path and name into ExifInterface, so that's why it says "/sdcard/dcim/100MEDIA/IMAG0020.jpg"instead of filename. Could that have anything to do with my problem?

回答1:

Solved it. Hardcoding the file path was the problem. I used the code

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);

to obtain picturePath which was then used in

ExifInterface exif = new ExifInterface(picturePath);