26

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.

Aniruddh Parihar
  • 3,072
  • 3
  • 21
  • 39
Rick de Jong
  • 343
  • 2
  • 4
  • 8
  • http://stackoverflow.com/questions/9564538/how-to-upload-images-to-php-server-and-store-in-phpmyadmin hope this will help – Maikel Mar 15 '13 at 12:35
  • @MaikelR Can you please help me with this detailed and Bounty added question? It would be really appreciate: https://stackoverflow.com/questions/62783444/why-does-multipart-pdf-is-not-able-to-upload-in-api-after-nougat-using-retrofit – Priyanka Singh Jul 10 '20 at 12:43

8 Answers8

63

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); 
}
Siddharth Lele
  • 27,623
  • 15
  • 98
  • 151
  • 2
    I've got "Failing delivering 'Result'. – Rick de Jong Mar 15 '13 at 13:00
  • @RickdeJong: Are you using the code exactly as in the post? Because if you are, it should work. – Siddharth Lele Mar 15 '13 at 13:02
  • @RickdeJong: At what line is that error in your `onActivityResult()`? – Siddharth Lele Mar 15 '13 at 13:04
  • Aah. You had me scared for a while. I thought if it doesn't work for you, my app must be broken too. ;-) – Siddharth Lele Mar 15 '13 at 13:10
  • @RickdeJong: Glad to have been of help. :-) – Siddharth Lele Mar 15 '13 at 13:10
  • 2
    @iceMAN You save my day :) – Adrien Cerdan Jun 21 '13 at 08:46
  • Error:(81, 27) error: cannot find symbol method getImageUri(Context,Bitmap) – Don Larynx Jun 03 '15 at 23:56
  • @DonLarynx: Have you also added the method `getImageUri` that is already shown in the answer? – Siddharth Lele Jun 09 '15 at 05:00
  • @delive: Can you explain a little more about what didn't work? Perhaps, you could post a new question referring to this answer and then link to it in a comment. – Siddharth Lele Oct 09 '15 at 11:29
  • Yes, your code not work in >5.0 is so easy, your code is 2013, you can't pretend that code work always .... –  Oct 09 '15 at 12:08
  • This is a correct line : Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);, but I put +1 because I was searching your "getImageUri" –  Oct 09 '15 at 12:12
  • @delive: I haven't pretended about anything at all. I asked you to explain the problem you were facing with the code because _Not work for me !_ doesn't really help me to help you. Anyway. Thanks for clarifying. – Siddharth Lele Oct 09 '15 at 12:26
  • This solution works great, quick question though @IceMAN - I can see that the image taken is high quality from within the gallery, but when I receive the image from the file path, it's very small, thus low quality when trying to blow it up (as the gallery would) is there any way to define the size of image I want in return? – em_ Dec 08 '15 at 16:06
  • @ElliotM: Not entirely sure why the code in question will return a small image. I am not scaling it down in it. Perhaps you could post your entire code (image picker) in a new question and link to it in a comment. I'll take a look at it. – Siddharth Lele Dec 09 '15 at 04:57
  • 1
    @IceMAN: I found out that `getData("data")` we only return the thumbnail of the image, see here: http://stackoverflow.com/questions/6448856/android-camera-intent-how-to-get-full-sized-photo. I was able to save the image temporarily then grab later on to solve this issue. Thanks anyways. – em_ Dec 09 '15 at 16:57
  • @SiddharthLele insertImage() creating thumbnail images. Is there any other way to get real picture instead of thumbnail? – Ajit Kumar Dubey Nov 10 '16 at 11:22
  • 1
    Remember to close the cursor – Oush Jul 14 '20 at 06:35
1

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);
        }  
Bhavesh Patadiya
  • 25,740
  • 15
  • 81
  • 107
1

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;
    }
Amit Gupta
  • 8,914
  • 1
  • 25
  • 33
0

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

Community
  • 1
  • 1
Emil Davtyan
  • 13,808
  • 5
  • 44
  • 66
0

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())));
            }




         }


    }
DeltaCap019
  • 6,532
  • 3
  • 48
  • 70
0

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)
}
Emre Tekin
  • 462
  • 7
  • 18
-1

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();
    }

}
-2

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));
        }
    }
Kamran
  • 465
  • 6
  • 9