chargerstriker
chargerstriker

Reputation: 496

Get filepath from inputStream

I am loading a picture from the gallery and setting it to a imageview, but I have a function that rotates the image and that function requires the images Uri. When I read in the picture from memory I use the following code

if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
        ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION);
    }else{
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, SELECT_FILE);
    }

then

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == SELECT_FILE){
        if(resultCode == RESULT_OK){
            imageUri = data.getData();
            InputStream imageStream = null;
            try {
                imageStream = getContentResolver().openInputStream(imageUri);
            }catch (IOException e){e.printStackTrace();}
            final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
            final Bitmap rotatedImage = rotateBitmap(selectedImage, **image file path**);
            profilePic.setImageBitmap(rotatedImage);
        }
    }
}

The function rotateBitmap() needs the image's file path, which I do not know how to get...

Upvotes: 2

Views: 3748

Answers (2)

Muhammad Jamal
Muhammad Jamal

Reputation: 442

using Uri you can get the path of the image ... Try this code, might help you

    Cursor cursor = getContentResolver().query(Use_Uri_Here, null, null, null, null); 
cursor.moveToFirst(); 
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
String imagePath = cursor.getString(idx); 

Upvotes: 0

Ashish Sahu
Ashish Sahu

Reputation: 1558

Use cursor:

Uri selectedImageUri = data.getData();
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImageUri, proj, null, null, null);
if (cursor.moveToFirst()) {
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    String  file_path = cursor.getString(column_index);
}
cursor.close();

Upvotes: 2

Related Questions