ExifInterface Latitude / Longitude返回null - Android

时间:2017-04-07 14:46:25

标签: java android coordinates exif

大家下午好,

我正在为Android开发一个非常简单的应用程序,它假设从图库中获取图片,显示它并在文本视图(纬度和经度)中显示其坐标。 我有一个ExifInterface objext,但标签(例如TAG_GPS_LATITUDE和TAG_GPS_LONGITUDE)返回null。 我在StackOverflow上尝试了很多不同的解决方案但没有一个能够工作,所以我想到了一个新的问题来展示我的代码。

MainActivity.java:

  public class MainActivity extends AppCompatActivity {

    private static int RESULT_LOAD_IMAGE = 1;
    TextView textView;
    ImageView imageView;
    Uri imgUri;
    String realPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.txtView);
        imageView = (ImageView) findViewById(R.id.imgView);
        Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
        buttonLoadImage.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View arg0){
                openGallery(arg0);
            }
        });
    }

    public void openGallery(View view){
        Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, RESULT_LOAD_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){

        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK){
            imgUri = data.getData();
            imageView.setImageURI(imgUri);
            realPath = getRealPathFromURI(this, imgUri);
            try {
                ExifInterface ei = new ExifInterface(realPath);
                textView.append("Latitude: " + ei.getAttribute(ExifInterface.TAG_GPS_LATITUDE) + " Longitude: " + ei.getAttribute(ExifInterface.TAG_GPS_LONGITUDE));

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

        }
    }

    public String getRealPathFromURI(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(contentUri,  proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
}

谢谢。

0 个答案:

没有答案