Get filepath and filename of selected gallery image in Android

后端 未结 9 2133
天命终不由人
天命终不由人 2020-11-27 04:47

I am creating an app which uploads a selected image from the gallery and uploads it to a web service. The webservice requires the filename of selected image plus a base64 e

9条回答
  •  猫巷女王i
    2020-11-27 05:35

    Try this to get data as well as file path and insert into folder.

    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (resultCode == RESULT_OK)
            {
                nav = data.getData();
                String[] projection = { MediaStore.Images.Media.DATA };
                Cursor cursor = managedQuery(nav, projection, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                String path= cursor.getString(column_index);
                Toast.makeText(getApplicationContext(), path, 500).show();
                mBitmap = android.provider.MediaStore.Images.Media.getBitmap(getContentResolver(), nav);
                insert(mBitmap);
    
                if (mBitmap != null) {  
                    mBitmap.recycle();  
                    mBitmap = null;  
                } 
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void insert(Bitmap finalBitmap) {
        File myDir=new File("/sdcard/saved_images");
        myDir.mkdirs();
    
        Random generator = new Random();
        int n = 10000;
        n = generator.nextInt(n);
        String fname = "Image-"+ n +".jpg";
        File file = new File (myDir, fname);
        if (file.exists ()) file.delete (); 
        try {
            FileOutputStream out = new FileOutputStream(file);
            finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            File dstFile = new File(file.getParent(), "." + file.getName());
            file.renameTo(dstFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

提交回复
热议问题