Reputation: 4659
I'm using image picker to select a image and then uploading this image to the server .
My code is working perfectly in all android devices except for Mi phones.
For all device Uri returned is of type : content://media/external/images/media/523 For Mi devices Uri returned is of type:file:///storage/emulated/0/DCIM/Camera/IMG_20160912_160415.jpg
The Cursor cursor = context.getContentResolver().query() returns null if the uri is not in format content://*
private void pickImage() {
Intent photoPickerIntent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
if (selectedImageUri != null) {
selectedImagePath = Utils.getImagePath(selectedImageUri, DepositBankWireActivity.this);
Log.i("uplaod", "selectedImagePath" + selectedImagePath);
}
}
public static String getImagePath(Uri uri, Context context) {
Log.i("getImagePath",""+uri+" mime "+getMimeType(uri,context));
String[] projection = {MediaStore.MediaColumns.DATA,
MediaStore.Images.ImageColumns.ORIENTATION};
Cursor cursor = context.getContentResolver().query(uri, projection, null, null,
null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Is there a standard way to implement image picker which returns the correct image path from uri eg /storage/emulated/0/Pictures/Screenshots/test.png for upload.
Upvotes: 0
Views: 1721
Reputation: 1006564
There is no requirement for the DATA
column of MediaStore
to give you a filesystem path that you can use. For example, the image might be on removable storage on Android 4.4+, which the MediaStore
can access, but you cannot. MediaStore
can also have in its index images that are not local to the device, but are from services like Google Photos (so I've been told).
So, your first step is to get rid of getImagePath()
, as it will be unreliable.
The simplest and most performant solution is to find a way to "compress the images and [do] a multipart image upload on the server" without filesystem access. For example, you have access to an InputStream
via openInputStream()
on ContentResolver
, and that will work for both types of Uri
shown in your question. Find some way to do your work using that InputStream
.
If you determine that this is not possible, you will need to get that InputStream
anyway and make a local copy of the content (e.g., in getCacheDir()
). Then, use your local copy, deleting it when you are done.
Upvotes: 1