如何从 Android Studio 中的图库中获取所选图像的位置(拍摄图像的位置)?
How to fetch the location(Location at which image was taken) of selected image from gallery in Android Studio?
我正在开发一个应用程序,它执行诸如使用相机拍照和查看照片等操作 taken.Now,我有一个按钮 onclick,它会转到我可以 select 的画廊image.After select 正在将图像加载到 activity 以及图像的位置。但是,任何照片的位置都是相同的(当前位置)selected。
我正在使用它来获取 location.But 无论哪个是我的图像 select 位置是我当前的位置。
GPSTRACKER.JAVA
package com.elno.bescomcoe;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import static android.content.ContentValues.TAG;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// Flag for GPS status
boolean isGPSEnabled = false;
// Flag for network status
boolean isNetworkEnabled = false;
// Flag for GPS status
boolean canGetLocation = false;
Location location; // Location
double latitude; // Latitude
double longitude; // Longitude
int geocoderMaxResults = 1;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context mContext) {
this.mContext = mContext;
getLocation();
}
@SuppressLint("MissingPermission")
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// Getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
System.out.println("GPS : " + isGPSEnabled);
// Getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
System.out.println("NETWORK : " + isNetworkEnabled);
if (isGPSEnabled) {
this.isGPSEnabled = true;
}
if (!isGPSEnabled && !isNetworkEnabled) {
// No network provider is enabled
System.out.println("Inside gps and network");
} else {
System.out.println("outside gps and network");
this.canGetLocation = true;
if (isNetworkEnabled) {
//ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 0);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// If GPS enabled, get latitude/longitude using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app.
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/Wi-Fi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog.
* On pressing the Settings button it will launch Settings Options.
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing the Settings button.
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// On pressing the cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
//Get list of Addresses by latitude and longitude
//return List<Adresses> - list of addresses or null
public List<Address> getGeocoderAddress(Context context) {
if (location != null) {
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try {
/**
* Geocoder.getFromLocation - Returns an array of Addresses
* that are known to describe the area immediately surrounding the given latitude and longitude.
*/
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);
return addresses;
} catch (IOException e) {
//e.printStackTrace();
Log.e(TAG, "Impossible to connect to Geocoder", e);
}
}
return null;
}
//Get the Address Line
//Return address line or null
public String getAddressLine(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
} else {
return null;
}
}
//Get the Locality
//Return the locality or null
public String getLocality(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
}
else {
return null;
}
}
/**
* Try to get Postal Code
* @return null or postalCode
*/
public String getPostalCode(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
} else {
return null;
}
}
/**
* Try to get CountryName
* @return null or postalCode
*/
public String getCountryName(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
} else {
return null;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}
而且,这是我的 Activity,我正在向其中加载 selected 图像和位置。
package com.elno.bescomcoe;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class ViewGalleryAcitvity extends AppCompatActivity {
private TextView LocationTextView;
private ImageView SelectedImageView;
GPSTracker gps;
double latitude ;
double longitude;
String country;
String city;
String postalcode;
String addressline;
Uri imageUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_gallery);
LocationTextView = findViewById(R.id.LoctextView);
SelectedImageView = findViewById(R.id.selectedimage);
Bundle bundle = getIntent().getExtras();
if(bundle != null){
imageUri = Uri.parse(bundle.getString("picture"));
SelectedImageView.setImageURI(imageUri);
gps = new GPSTracker(getApplicationContext());
if(gps.canGetLocation())
{
latitude = gps.getLatitude();
longitude = gps.getLongitude();
country = gps.getCountryName(this);
city = gps.getLocality(this);
postalcode = gps.getPostalCode(this);
addressline = gps.getAddressLine(this);
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
LocationTextView.setText("Latitude - "+latitude+"\nLongitude - "+longitude);
} else {
// Can't get location.
}
}
else {
//Bundle is empty
}
}
}
现在我需要有关如何获取图像拍摄位置的帮助,而不仅仅是我当前的位置。
您可以使用 ExifInterface
获取图像属性
示例:
ExifInterface exif = new ExifInterface(filepath);
String LATITUDE = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
String LATITUDE_REF = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
String LONGITUDE = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
String LONGITUDE_REF = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);
或
ExifInterface exif = new ExifInterface(filepath);
float[] latLong = new float[2];
boolean hasLatLong = exif.getLatLong(latLong)
if (hasLatLong) {
System.out.println("Latitude: " + latLong[0]);
System.out.println("Longitude: " + latLong[1]);
}
ExifInterface exif = new ExifInterface(getContentResolver().openInputStream(selectedImage));
float[] latLong = new float[2];
boolean hasLatLong = exif.getLatLong(latLong)
if (hasLatLong) {
System.out.println("Latitude: " + latLong[0]);
System.out.println("Longitude: " + latLong[1]);
}
看看这个 link 以便更好地理解。
另外,最好参考文档here.
我正在开发一个应用程序,它执行诸如使用相机拍照和查看照片等操作 taken.Now,我有一个按钮 onclick,它会转到我可以 select 的画廊image.After select 正在将图像加载到 activity 以及图像的位置。但是,任何照片的位置都是相同的(当前位置)selected。
我正在使用它来获取 location.But 无论哪个是我的图像 select 位置是我当前的位置。
GPSTRACKER.JAVA
package com.elno.bescomcoe;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import static android.content.ContentValues.TAG;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// Flag for GPS status
boolean isGPSEnabled = false;
// Flag for network status
boolean isNetworkEnabled = false;
// Flag for GPS status
boolean canGetLocation = false;
Location location; // Location
double latitude; // Latitude
double longitude; // Longitude
int geocoderMaxResults = 1;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context mContext) {
this.mContext = mContext;
getLocation();
}
@SuppressLint("MissingPermission")
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// Getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
System.out.println("GPS : " + isGPSEnabled);
// Getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
System.out.println("NETWORK : " + isNetworkEnabled);
if (isGPSEnabled) {
this.isGPSEnabled = true;
}
if (!isGPSEnabled && !isNetworkEnabled) {
// No network provider is enabled
System.out.println("Inside gps and network");
} else {
System.out.println("outside gps and network");
this.canGetLocation = true;
if (isNetworkEnabled) {
//ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 0);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// If GPS enabled, get latitude/longitude using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app.
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/Wi-Fi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog.
* On pressing the Settings button it will launch Settings Options.
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing the Settings button.
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// On pressing the cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
//Get list of Addresses by latitude and longitude
//return List<Adresses> - list of addresses or null
public List<Address> getGeocoderAddress(Context context) {
if (location != null) {
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try {
/**
* Geocoder.getFromLocation - Returns an array of Addresses
* that are known to describe the area immediately surrounding the given latitude and longitude.
*/
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);
return addresses;
} catch (IOException e) {
//e.printStackTrace();
Log.e(TAG, "Impossible to connect to Geocoder", e);
}
}
return null;
}
//Get the Address Line
//Return address line or null
public String getAddressLine(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
} else {
return null;
}
}
//Get the Locality
//Return the locality or null
public String getLocality(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
}
else {
return null;
}
}
/**
* Try to get Postal Code
* @return null or postalCode
*/
public String getPostalCode(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
} else {
return null;
}
}
/**
* Try to get CountryName
* @return null or postalCode
*/
public String getCountryName(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
} else {
return null;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}
而且,这是我的 Activity,我正在向其中加载 selected 图像和位置。
package com.elno.bescomcoe;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class ViewGalleryAcitvity extends AppCompatActivity {
private TextView LocationTextView;
private ImageView SelectedImageView;
GPSTracker gps;
double latitude ;
double longitude;
String country;
String city;
String postalcode;
String addressline;
Uri imageUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_gallery);
LocationTextView = findViewById(R.id.LoctextView);
SelectedImageView = findViewById(R.id.selectedimage);
Bundle bundle = getIntent().getExtras();
if(bundle != null){
imageUri = Uri.parse(bundle.getString("picture"));
SelectedImageView.setImageURI(imageUri);
gps = new GPSTracker(getApplicationContext());
if(gps.canGetLocation())
{
latitude = gps.getLatitude();
longitude = gps.getLongitude();
country = gps.getCountryName(this);
city = gps.getLocality(this);
postalcode = gps.getPostalCode(this);
addressline = gps.getAddressLine(this);
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
LocationTextView.setText("Latitude - "+latitude+"\nLongitude - "+longitude);
} else {
// Can't get location.
}
}
else {
//Bundle is empty
}
}
}
现在我需要有关如何获取图像拍摄位置的帮助,而不仅仅是我当前的位置。
您可以使用 ExifInterface
获取图像属性示例:
ExifInterface exif = new ExifInterface(filepath);
String LATITUDE = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
String LATITUDE_REF = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
String LONGITUDE = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
String LONGITUDE_REF = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);
或
ExifInterface exif = new ExifInterface(filepath);
float[] latLong = new float[2];
boolean hasLatLong = exif.getLatLong(latLong)
if (hasLatLong) {
System.out.println("Latitude: " + latLong[0]);
System.out.println("Longitude: " + latLong[1]);
}
ExifInterface exif = new ExifInterface(getContentResolver().openInputStream(selectedImage));
float[] latLong = new float[2];
boolean hasLatLong = exif.getLatLong(latLong)
if (hasLatLong) {
System.out.println("Latitude: " + latLong[0]);
System.out.println("Longitude: " + latLong[1]);
}
看看这个 link 以便更好地理解。
另外,最好参考文档here.