Get file path of image on Android

后端 未结 8 1737
长发绾君心
长发绾君心 2020-11-30 09:48

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 voi         


        
相关标签:
8条回答
  • 2020-11-30 10:13

    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())));
                }
    
    
    
    
             }
    
    
        }
    
    0 讨论(0)
  • 2020-11-30 10:22

    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); 
    }
    
    0 讨论(0)
  • 2020-11-30 10:25

    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;
        }
    
    0 讨论(0)
  • 2020-11-30 10:26

    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)
    }
    
    0 讨论(0)
  • 2020-11-30 10:29

    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

    0 讨论(0)
  • 2020-11-30 10:34

    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);
            }  
    
    0 讨论(0)
提交回复
热议问题