Getting path of captured image in Android using camera intent - android

I have been trying to get path of captured image in order to delete image. Found many answers on StackOverflow but none of them are working for me. I got the following answer:
private String getLastImagePath() {
final String[] imageColumns = { MediaStore.Images.Media._ID,
MediaStore.Images.Media.DATA };
final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
Cursor imageCursor = POS.this.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns,
null, null, imageOrderBy);
if (imageCursor.moveToFirst()) {
// int id = imageCursor.getInt(imageCursor
// .getColumnIndex(MediaStore.Images.Media._ID));
String fullPath = imageCursor.getString(imageCursor
.getColumnIndex(MediaStore.Images.Media.DATA));
return fullPath;
} else {
return "";
}
}
This code works in Samsung tab but doesn't work in Lenovo tab and i-ball tab.
So, can anyone help me find another solution to do the same?
Any help will be appreciated. Thank you.
This is my onActivityResult:
if (requestCode == CmsInter.CAMERA_REQUEST && resultCode == RESULT_OK) {
//Bitmap photo = null;
//photo = (Bitmap) data.getExtras().get("data");
String txt = "";
if (im != null) {
String result = "";
//im.setImageBitmap(photo);
im.setTag("2");
int index = im.getId();
String path = getLastImagePath();
try {
bitmap1 = BitmapFactory.decodeFile(path, options);
bitmap = Bitmap.createScaledBitmap(bitmap1, 512, 400, false);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] bytData = baos.toByteArray();
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
result = Base64.encode(bytData);
bytData = null;
} catch (OutOfMemoryError ooM) {
System.out.println("OutOfMemory Exception----->" + ooM);
bitmap1.recycle();
bitmap.recycle();
} finally {
bitmap1.recycle();
bitmap.recycle();
}
}
}

Try like this
Pass Camera Intent like below
Intent intent = new Intent(this);
startActivityForResult(intent, REQ_CAMERA_IMAGE);
And after capturing image Write an OnActivityResult as below
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), photo);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File finalFile = new File(getRealPathFromURI(tempUri));
System.out.println(mImageCaptureUri);
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
String path = "";
if (getContentResolver() != null) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
path = cursor.getString(idx);
cursor.close();
}
}
return path;
}
And check log.
Edit:
Lots of people are asking how to not get a thumbnail. You need to add this code instead for the getImageUri method:
public Uri getImageUri(Context inContext, Bitmap inImage) {
Bitmap OutImage = Bitmap.createScaledBitmap(inImage, 1000, 1000,true);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), OutImage, "Title", null);
return Uri.parse(path);
}
The other method Compresses the file. You can adjust the size by changing the number 1000,1000

There is a solution to create file (on external cache dir or anywhere else) and put this file's uri as output extra to camera intent - this will define path where taken picture will be stored.
Here is an example:
File file;
Uri fileUri;
final int RC_TAKE_PHOTO = 1;
private void takePhoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = new File(getActivity().getExternalCacheDir(),
String.valueOf(System.currentTimeMillis()) + ".jpg");
fileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
getActivity().startActivityForResult(intent, RC_TAKE_PHOTO);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_TAKE_PHOTO && resultCode == RESULT_OK) {
//do whatever you need with taken photo using file or fileUri
}
}
}
Then if you don't need the file anymore, you can delete it using file.delete();
By the way, files from cache dir will be removed when user clears app's cache from apps settings.

Try this method to get path of original image captured by camera.
public String getOriginalImagePath() {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, null, null, null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToLast();
return cursor.getString(column_index_data);
}
This method will return path of the last image captured by camera. So this path would be of original image not of thumbnail bitmap.

Here I updated the sample code in Kotlin. Please note on Nougat and above version Uri.fromFile(file) is not working and it crashes the app for that need to implement FileProvider which is safest way to send files from intent. For implementing this refer this answer or this article
private fun takePhotoFromCamera() {
val isDeviceSupportCamera: Boolean = this.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)
if (isDeviceSupportCamera) {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
file = File(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS + "/attachments")!!.path,
System.currentTimeMillis().toString() + ".jpg")
// fileUri = Uri.fromFile(file)
fileUri = FileProvider.getUriForFile(this, this.applicationContext.packageName + ".provider", file!!)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
}
startActivityForResult(takePictureIntent, Constants.REQUEST_CODE_IMAGE_CAPTURE)
}
} else {
Toast.makeText(this, this.getString(R.string.camera_not_supported), Toast.LENGTH_SHORT).show()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
if(requestCode == Constants.REQUEST_CODE_IMAGE_CAPTURE) {
realPath = file?.path
//do what ever you want to do
}
}
}

Please refer to Google Documentation:
Camera - Photo Basics

try this
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(mCapturedImageURI, projection,
null, null, null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
image_path = cursor.getString(column_index_data);
Log.e("path of image from CAMERA......******************.........",
image_path + "");
for capturing image:
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);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
values.clear();

Related

Take photo intent returns null on data

I'm creating an app to take photos and delete image from gallery after specific process. Here is my code
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(takePictureIntent, requestCode);
}
And I handle the result just like this
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
image1 = (Bitmap) extras.get(IMAGE_BUNDLE_NAME);
imageView1.setImageBitmap(image1);
imageUri1 = data.getData();
}
}
The problem is that data.getData(); returns null in some devices. I tried to replace URI with this code
imageUri1 = getImageUri(getActivity(), image1);
And this method
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
Whe I use this Uri I can't delete file from device. This is how I delete images
private void deleteFileFromMediaStore(final ContentResolver contentResolver, int requestCode) {
String canonicalPath;
File fdelete = new File(imageUri1.getPath());
if(fdelete != null){
try {
canonicalPath = fdelete.getCanonicalPath();
} catch (IOException e) {
canonicalPath = fdelete.getAbsolutePath();
}
final Uri uri = MediaStore.Files.getContentUri(Constants.EXTERNAL_STORAGE_CONSTANT);
final int result = contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[] {canonicalPath});
if (result == 0) {
final String absolutePath = fdelete.getAbsolutePath();
if (!absolutePath.equals(canonicalPath)) {
contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[]{absolutePath});
}
}
}
}
How can I delete the photo or how can I make data.getData() non null on all devices?
The problem is that data.getData(); returns null in some devices
It will return null with most camera apps, as it is supposed to return null.
How can I delete the photo
Save the thumbnail photo to a file (compress() and a FileOutputStream).
Or, use EXTRA_OUTPUT to request that the camera app save a full-size photo to a location that you specify (e.g., using a FileProvider-supplied Uri).
Or, use a library like Fotoapparat to take photos directly in your app, rather than relying on one of hundreds of camera apps.
how can I make "data.getData()" non null on all devices?
You can't.

Get path of Image clicked by Android Camera

I need to click an image using the default camera app on an android device and get the path of the image just clicked. I have taken help from this post
stackoverflow forum link
And my code is as follows
public void MarkIn(View view) {
String fileName = "temp.jpg";
final int CAPTURE_PICTURE_INTENT = 1;
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(intent, CAPTURE_PICTURE_INTENT);
String imagePath = capturedImageFilePath;
// .....some code.....
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = null;
cursor = getApplicationContext().getContentResolver().query(mCapturedImageURI, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
capturedImageFilePath = cursor.getString(column_index_data);
}
}
The system isn't waiting for Activity to get completed. As my ...some code... in the above snippet is depenedent on the file path, I am getting null pointer exception.
How to make the code execution wait till the activity is completed.
You should first get the image bitmap on image click and then convert that bitmap into uri using this code.:-
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
try this and let me know.
This is Probably as you are using sdk version 19 or above.Android has changed the way we access data from KitKat.

onActivityResult returns null data for an Image Capture

#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
filePath = getOutputMediaFile(FileColumns.MEDIA_TYPE_IMAGE);
File file = new File(filePath);
Uri output = Uri.fromFile(file);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, output);
startActivityForResult(i, RETURN_FILE_PATH);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//data is always null here.
//requestCode = RETURN_FILE_PATH;
//resultCode = Activity.RESULT_OK;
}
I checked the values for file and output Uri, both are fine and the captured image actually exists at that location.
But the data returned in onActivityResult is always null even after capturing the image.
EDIT:
I checked this question:
onActivityResult returns with data = null
which says:
Whenever you save an image by passing EXTRAOUTPUT with camera intent
the data parameter inside the onActivityResult always return null. So,
instead of using data to retrieve the image , use the filepath to
retrieve the Bitmap.
and maybe that solution will work for me. But the above code of mine was a working code until now for the same scenario.
According to this post data is null when you pre insert a uri. That means you already defined your output uri here:
i.putExtra(MediaStore.EXTRA_OUTPUT, output);
So when you get a Activity.RESULT_OK; just load the taken photo by its known url.
Try this code this is working for me.
else if(requestCode == Constant.PICK_FROM_CAMERA)
{
if (resultCode == Activity.RESULT_OK)
{
if(data!=null)
{
mImageCaptureUri = data.getData();
//path= mImageCaptureUri.getPath();
try
{
path = getPath(mImageCaptureUri,Wonderlistpage.this); //from Gallery
}
catch(Exception e)
{
path = mImageCaptureUri.getPath();
Log.i("check image attach or not", e.toString());
}
String arr[] = path.split("/");
int i;
String k = null;
for(i=0;i<arr.length;i++)
{
k=arr[i];
}
photoname="_"+String.valueOf(System.currentTimeMillis()) +k;
if(setprofileimage_sendimagewithmessage==1)
{
performCrop(mImageCaptureUri);
}
else
{
loading_details="CAMERA";
new performBackgroundTask33().execute();
}
}
else
{
file1 = new File(Environment.getExternalStorageDirectory(),
String.valueOf(System.currentTimeMillis()) + "_FromCamera.jpg");
Uri mImageCaptureUri = Uri.fromFile(file1);
try
{
path = getPath(mImageCaptureUri,Wonderlistpage.this); //from Gallery
}
catch(Exception e)
{
path = mImageCaptureUri.getPath();
Log.i("check image attach or not", e.toString());
}
String arr[] = path.split("/");
int i;
String k = null;
for(i=0;i<arr.length;i++)
{
k=arr[i];
}
photoname="_"+String.valueOf(System.currentTimeMillis()) +k;
if(setprofileimage_sendimagewithmessage==1)
{
performCrop(mImageCaptureUri);
}
else
{
loading_details="CAMERA";
new performBackgroundTask33().execute();
}
}
//new UploadTask().execute();
}
}
Try following code
{
final String[] imageColumns = { MediaStore.Images.Media._ID,MediaStore.Images.Media.DATA };
final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
Cursor imageCursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns, null, null, imageOrderBy);
imageCursor.moveToFirst();
do {
String fullPath = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
if (fullPath.contains("DCIM")) {
//get bitmap from fullpath here.
return;
}
}
while (imageCursor.moveToNext());
Just Put this code into your onActivityResult. The same problem i have faced on some devices and this solved my problem. Hope this will also help you.
try {
Uri selectedImage = output;
if (selectedImage == null)
return;
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();
} catch (Exception e) {
return;
}
You will get the Picture path in picturePath variable and Uri in selectedImage Variable.
If your activity has launchmode as singleInstance in your manifest then you would face this issue. Try changing it. As it cancels the result everytime.

Get file path of image on Android

I have an app that can make pictures and upload them. The upload requires the file path of the photo but I can't get it.
This is my code:
public void maakfoto (View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
System.out.println(mImageCaptureUri);
}
}
Please help me to get the file path.
Posting to Twitter needs the image's actual path on the device to be sent in the request to post. I was finding it mighty difficult to get the actual path and more often than not I would get the wrong path.
To counter that, once you have a Bitmap, I use that to get the URI from using the getImageUri(). Subsequently, I use the tempUri Uri instance to get the actual path as it is on the device.
This is production code and naturally tested. ;-)
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), photo);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File finalFile = new File(getRealPathFromURI(tempUri));
System.out.println(mImageCaptureUri);
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
Try out with mImageCaptureUri.getPath(); By Below Way :
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
//Get your Image Path
String Path=mImageCaptureUri.getPath();
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
System.out.println(mImageCaptureUri);
}
In order to take a picture you have to determine a path where you would like the image saved and pass that as an extra in the intent, for example:
private void capture(){
String directoryPath = Environment.getExternalStorageDirectory() + "/" + IMAGE_DIRECTORY + "/";
String filePath = directoryPath+Long.toHexString(System.currentTimeMillis())+".jpg";
File directory = new File(directoryPath);
if (!directory.exists()) {
directory.mkdirs();
}
this.capturePath = filePath; // you will process the image from this path if the capture goes well
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra( MediaStore.EXTRA_OUTPUT, Uri.fromFile( new File(filePath) ) );
startActivityForResult(intent, REQUEST_CAPTURE);
}
I just copied the above portion from another answer I gave.
However to warn you there are a lot of inconsitencies with image capture behavior between devices that you should look out for.
Here is an issue I ran into on some HTC devices, where it would save in the location I passed and in it's default location resulting in duplicate images on the device:
Deleting a gallery image after camera intent photo taken
I am doing this on click of Button.
private static final int CAMERA_PIC_REQUEST = 1;
private View.OnClickListener OpenCamera=new View.OnClickListener() {
#Override
public void onClick(View paramView) {
// TODO Auto-generated method stub
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
NewSelectedImageURL=null;
//outfile where we are thinking of saving it
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
String newPicFile = RecipeName+ df.format(date) + ".png";
String outPath =Environment.getExternalStorageDirectory() + "/myFolderName/"+ newPicFile ;
File outFile = new File(outPath);
CapturedImageURL=outFile.toString();
Uri outuri = Uri.fromFile(outFile);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, outuri);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
};
You can get the URL of the recently Captured Image from variable CapturedImageURL
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//////////////////////////////////////
if (requestCode == CAMERA_PIC_REQUEST) {
// do something
if (resultCode == RESULT_OK)
{
Uri uri = null;
if (data != null)
{
uri = data.getData();
}
if (uri == null && CapturedImageURL != null)
{
uri = Uri.fromFile(new File(CapturedImageURL));
}
File file = new File(CapturedImageURL);
if (!file.exists()) {
file.mkdir();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+Environment.getExternalStorageDirectory())));
}
}
}
use this function to get the capture image path
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Uri mImageCaptureUri = intent.getData();
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
System.out.println(mImageCaptureUri);
//getImgPath(mImageCaptureUri);// it will return the Capture image path
}
}
public String getImgPath(Uri uri) {
String[] largeFileProjection = { MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA };
String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
Cursor myCursor = this.managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
largeFileProjection, null, null, largeFileSort);
String largeImagePath = "";
try {
myCursor.moveToFirst();
largeImagePath = myCursor
.getString(myCursor
.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
} finally {
myCursor.close();
}
return largeImagePath;
}
You can do like that In Kotlin If you need kotlin code in the future
val myUri = getImageUri(applicationContext, myBitmap!!)
val finalFile = File(getRealPathFromURI(myUri))
fun getImageUri(inContext: Context, inImage: Bitmap): Uri {
val bytes = ByteArrayOutputStream()
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
val path = MediaStore.Images.Media.insertImage(inContext.contentResolver, inImage, "Title", null)
return Uri.parse(path)
}
fun getRealPathFromURI(uri: Uri): String {
val cursor = contentResolver.query(uri, null, null, null, null)
cursor!!.moveToFirst()
val idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
return cursor.getString(idx)
}
To get the path of all images in android I am using following code
public void allImages()
{
ContentResolver cr = getContentResolver();
Cursor cursor;
Uri allimagessuri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Images.Media._ID + " != 0";
cursor = cr.query(allsongsuri, STAR, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String fullpath = cursor.getString(cursor
.getColumnIndex(MediaStore.Images.Media.DATA));
Log.i("Image path ", fullpath + "");
} while (cursor.moveToNext());
}
cursor.close();
}
}
Simple Pass Intent first
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
And u will get picture path on u onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
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();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}

Low picture/image quality when capture from camera

I have one problem. When I try to get picture from camera, the quality is very low.
At first, capture the picture using camera, than save to the directory and at the same time get that picture and show in my app.The picture saved inside directory is a fine quality but when I get it from directory, the quality is low. below is my sample code :
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == CAMERA_PIC_REQUEST) {
Bitmap thumbnail = (Bitmap) intent.getExtras().get("data");
if (g==1)
{
ImageView myImage = (ImageView) findViewById(R.id.img5);
myImage.setImageBitmap(thumbnail);
View a = findViewById(R.id.img5);
a.setVisibility(View.VISIBLE);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byteArray1 = stream.toByteArray();
}
}
any solution/suggestion?
Thanks :)
Solved
The problem solved when I follow the code given by Antrromet below
I have used the following code and this works perfectly fine for me.
values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From your Camera");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, PICTURE_RESULT);
and also
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICTURE_RESULT:
if (requestCode == PICTURE_RESULT)
if (resultCode == Activity.RESULT_OK) {
try {
thumbnail = MediaStore.Images.Media.getBitmap(
getContentResolver(), imageUri);
imgView.setImageBitmap(thumbnail);
imageurl = getRealPathFromURI(imageUri);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
and
public String getRealPathFromURI(Uri contentUri) {
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);
}
I will give you something that work for me. I asked the same !
Solution to save a picture in a specific folder without lost quality
I FOUND THE SOLUTION:
//Create a new folder code:
String path = String.valueOf(Environment.getExternalStorageDirectory()) + "/your_name_folder";
try {
File ruta_sd = new File(path);
File folder = new File(ruta_sd.getAbsolutePath(), nameFol);
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
Toast.makeText(MainActivity.this, "Carpeta Creada...", Toast.LENGTH_SHORT).show();
}
} catch (Exception ex) {
Log.e("Carpetas", "Error al crear Carpeta a tarjeta SD");
}
Intent i = new Intent(MainActivity.this, MainActivity.class);
startActivity(i);
finish();//agregue este
//Method to take a Picture
public void clickFoto(View view) {
takePic();
}
//takePic()
private void takePic() {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
*File file = new File(Environment.getExternalStorageDirectory(), "/your_name_folder/a" + "/photo_" + timeStamp + ".png");*
imageUri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, PICTURE_RESULT);
}
//onActivityResult
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICTURE_RESULT:
if (requestCode == PICTURE_RESULT)
if (resultCode == Activity.RESULT_OK) {
try {
Bitmap thumbnail = MediaStore.Images.Media.getBitmap(
getContentResolver(), imageUri);
imgFoto.setImageBitmap(thumbnail);
imageurl = getRealPathFromURI(imageUri);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
// getRealPathFromUri
public String getRealPathFromURI(Uri contentUri) {
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);
}
Add the photo to a gallery
.
.
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
for more detail : https://developer.android.com/training/camera/photobasics.html

Categories

Resources