I am trying to fetch location of captured picture from camera. When I tried Exif interface but still return null value from photos.Please somebody help...
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 100);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
img1 = cursor.getString(cursor.getColumnIndex(filePath[0]));
ExifInterface exif = null;
try {
exif = new ExifInterface(img1);
} catch (IOException e) {
e.printStackTrace();
}
String lat = ExifInterface.TAG_GPS_LATITUDE;
String lat_data = exif.getAttribute(lat);
Log.e("MYDATA", lat_data);
cursor.close();
Toast.makeText(this, "Image Uploaded", Toast.LENGTH_SHORT).show();
}
Use Content resolver to build ExifInterface with inputStream
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode != Activity.RESULT_OK) {
return;
}
final Uri originalUri = intent.getData();
try {
final InputStream inputStream = getContext().getContentResolver().openInputStream(originalUri);
final android.support.media.ExifInterface exif = new android.support.media.ExifInterface(inputStream);
final double[] latLong = exif.getLatLong();
Log.v(LOG_TAG, "Image selected at position: " + latLong[0] + " : " + latLong[1]);
} catch (IOException e) {
Log.w(LOG_TAG, "Error when getting location from image", e);
}
}
Support lib import
compile 'com.android.support:exifinterface:x.x.x'
Related
This is my code for file chooser
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
then onActivityResult()
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), filePath);
System.out.println(bitmap.getByteCount());
int w = bitmap.getWidth();
int h = bitmap.getHeight();
if (w!= 512 || h!= 512)
{
txvLogoError.setText("Invalid image dimensions. Please choose another.");
}
else
{
txvLogoError.setText("");
imbAppLogo.setPadding(10,10,10,10);
imbAppLogo.setImageBitmap(bitmap);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
my question is, how can I get the exact file size of the image selected? I tried File.length() but the result is 0.
Try this .
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
int dataSize=0;
if (requestCode == 2 && resultCode == RESULT_OK)
{
Uri uri = data.getData();
String scheme = uri.getScheme();
System.out.println("Scheme type " + scheme);
if(scheme.equals(ContentResolver.SCHEME_CONTENT))
{
try {
InputStream fileInputStream=getApplicationContext().getContentResolver().openInputStream(uri);
dataSize = fileInputStream.available();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("File size in bytes"+dataSize);
}
else if(scheme.equals(ContentResolver.SCHEME_FILE))
{
String path = uri.getPath();
try {
f = new File(path);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("File size in bytes"+f.length());
}
}
}
try the following,
File f = new File(filePath.getPath());
long size = f.length();
Otherwise you can try
Cursor returnCursor = getContentResolver().query(filePath, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
I just need to covert the path in file to InputStream here is my code. I select the path by calling Intent but it always gives me filenotfoundexception
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FROM_FILE && resultCode == RESULT_OK) {
File file = new File(Environment.getExternalStorageDirectory(), data.getData().toString());
Uri path = Uri.fromFile(file);
File fpath=new File(path.toString());
try {
InputStream myfile=new FileInputStream(fpath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
thanks for help in advance...
try this:
Uri uri = data.getData();
ContentResolver cr = this.getContentResolver();
try {
InputStream myfile=cr.openInputStream(uri));;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Intent intent = new Intent();
intent.setType("image/*");
//intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == getActivity(). RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), filePath);
//Setting the Bitmap to ImageView
Glide.with(getActivity()).load(filePath).asBitmap().placeholder(R.drawable.ic_launcher).into(avatarContainer);
//avatarContainer.setImageBitmap(bitmap);
//uploadFile(filePath.getPath());
try {
uploadFile(getPath(filePath));
} catch (Exception e) {
Config.displayToast("Please Select Image From Gallary");
alertDialog.dismiss();
ServerRequest.dismissDialogBox(context);
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}else if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE && resultCode == getActivity() .RESULT_OK){
String filepath = fileUri.getPath();
Log.d("Filepath is",""+filepath);
BitmapFactory.Options options = new BitmapFactory.Options();
// down sizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(filepath, options);
//avatarContainer.setImageBitmap(bitmap);
Glide.with(getActivity()).load(filepath).asBitmap().placeholder(R.drawable.ic_launcher).into(avatarContainer);
uploadFile(filepath);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
In my Activity A, there is an ImageView and a Button. When the button is clicked, it goes to activeTakePhoto(). The imgUri gets displayed but nothing is displayed in my ImageView.
private void activeTakePhoto() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver()
.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
takePictureIntent
.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (requestCode == RESULT_LOAD_IMAGE &&
resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver()
.query(selectedImage, filePathColumn, null, null,
null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
}
case REQUEST_IMAGE_CAPTURE:
if (requestCode == REQUEST_IMAGE_CAPTURE &&
resultCode == RESULT_OK) {
File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
ImageView imgView=(ImageView)findViewById(R.id.imageView);
Uri imgUri=Uri.fromFile(picture);
imgView.setImageURI(imgUri);
Toast.makeText(getApplication(),imgUri+"",Toast.LENGTH_LONG).show();
}
}
}
You can try this code,it may help:
#Override
public void onClick(View v) {
if (v == imgCamera) {
Toast.makeText(getApplicationContext(), "open camera", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
}
}//on click
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("RESULT CODE", "--" + resultCode);
if (resultCode == RESULT_OK) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
//to generate random file name
String fileName = "tempimg.jpg";
try {
Bitmap photo = (Bitmap) data.getExtras().get("data");
//captured image set in imageview
imageView.setImageBitmap(photo);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
in activeTakePhoto
Replace
String fileName = "temp.jpg";
with
fileName=Environment.getExternalStorageDirectory().getAbsolutePath() + "/temp.jpg"
hello very good noon to all.Actually i want to select an image from gallery and then i want to save the selected image in Sdcard which is available in android device.
pick image from Sd card:
Intent mediaChooser = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
// comma-separated MIME types
mediaChooser.setType("image/*");
startActivityForResult(mediaChooser, RESULT_LOAD_WATER_IMAGE);
And On Activity Result :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
String path;
path = getRealPathFromURI(data.getData());
}
break;
}
Implementation Of getRealPathFromURI:
public String getRealPathFromURI(Uri contentUri) {
try {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} catch (Exception e) {
return contentUri.getPath();
}
}
Save Image To Sd Card On Click:
// TODO Auto-generated method stub
String root = Environment.getExternalStorageDirectory()
.toString();
File myDir = new File(root + "/Your Folder Name");
myDir.mkdirs();
String fname = "Your File Name";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try
{
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("error" + e);
}
Using the code below, you can pick up an image from gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
After that, the picked up image will be return by the onActivityResult() method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == Activity.RESULT_OK && requestCode == PICK_IMAGE && data != null && data.getData() != null) {
Uri _uri = data.getData();
Cursor cursor = getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
//Get the image file path
final String imageFilePath = cursor.getString(0);
cursor.close();
//save it the sdcard
saveToSDCard(imageFilePath);
}
super.onActivityResult(requestCode, resultCode, data);
}
This code worked on samsung before but now that i'm using Nexus One with Android 2.3.6, it's crashing as soon as I take a picture and click ok or choose a photo from gallery. Stacktrace shows a null pointer exception on the Uri.
My code for the activating the camera is as follows:
public void activateCamera(View view){
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// start the image capture Intent
startActivityForResult(i, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode == CHOOSE_IMAGE_ACTIVITY_REQUEST_CODE || requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
&& resultCode == RESULT_OK && null != data) {
selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bits = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = inSampleSize;
try {
bits = BitmapFactory.decodeStream(new FileInputStream(picturePath),null,options);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Any idea what could be the problem?
Thanks!
You have to tell the camera, where to save the picture and remeber the uri yourself:
private Uri mMakePhotoUri;
private File createImageFile() {
// return a File object for your image.
}
private void makePhoto() {
try {
File f = createImageFile();
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mMakePhotoUri = Uri.fromFile(f);
i.putExtra(MediaStore.EXTRA_OUTPUT, mMakePhotoUri);
startActivityForResult(i, REQUEST_MAKE_PHOTO);
} catch (IOException e) {
Log.e(TAG, "IO error", e);
Toast.makeText(getActivity(), R.string.error_writing_image, Toast.LENGTH_LONG).show();
}
}
#Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_MAKE_PHOTO:
if (resultCode == Activity.RESULT_OK) {
// do something with mMakePhotoUri
}
return;
default: // do nothing
super.onActivityResult(requestCode, resultCode, data);
}
}
You should save the value of mMakePhotoUri over instance states withing onCreate() and onSaveInstanceState().
Inject this extra into the Intent that called onActivityResult and the system will do all the heavy lifting for you.
File f = createImageFile();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
Doing this makes it as easy as this to retrieve the photo as a bitmap.
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
mImageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(mImageBitmap);
}
dont pass any extras, just define the path where you have placed or saved the file directly in onActivityResult
public void openCamera() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = createImageFile();
boolean isDirectoryCreated = file.getParentFile().mkdirs();
Log.d("", "openCamera: isDirectoryCreated: " + isDirectoryCreated);
if (Build.VERSION.SDK_INT >= 23) {
tempFileUri = FileProvider.getUriForFile(getActivity().getApplicationContext(),
"com.scanlibrary.provider", // As defined in Manifest
file);
} else {
tempFileUri = Uri.fromFile(file);
}
try
{
cameraIntent.putExtra("return-data", true);
startActivityForResult(cameraIntent, ScanConstants.START_CAMERA_REQUEST_CODE);
}
catch (Exception e)
{
}
}
private File createImageFile() {
clearTempImages();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new
Date());
File file = new File(ScanConstants.IMAGE_PATH, "IMG_" + timeStamp +
".jpg");
fileUri = Uri.fromFile(file);
return file;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = null ;
if (resultCode == Activity.RESULT_OK ) {
try {
if (Build.VERSION.SDK_INT >= 23) {
tempFileUri = FileProvider.getUriForFile(getActivity().getApplicationContext(),
"com.scanlibrary.provider", // As defined in Manifest
file);
} else {
tempFileUri = Uri.fromFile(file);
}
bitmap = getBitmap(tempFileUri);
bitmap = getBitmap(data.getData());
} catch (Exception e) {
e.printStackTrace();
}
} else {
getActivity().finish();
}
if (bitmap != null) {
postImagePick(bitmap);
}
}