问题
I want to upload an image from gallery and show it on my Android app. This works fine if I select an image from the screenshot folder for example. But when I select an image from the folder where the pics, taken with the phone camera, are stored, it does not work.
public void UploadPicture(View v) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 1);
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
imageView.setImageURI(selectedImage);
}
break;
}
}
回答1:
In my opinion, these problems can be solved by ImagePicker Libraries such as Ucrop. Ucrop Library For Android
Make sure you have Runtime permission Handled. For easier permission handling you can use Dexter Dexter
Make sure u have External Storage Read permission in your manifest file. You may also require both Read/Write permission if you want to take image from camera.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Note: for android version above Pie paste these attributes in application tag in manifest.xml :
<application
android:preserveLegacyExternalStorage="true"
android:requestLegacyExternalStorage="true"
... >
...
...
</application>
回答2:
Make sure you have give run time permission to choose image from gallery and permissions in the manifest.
Use android:requestLegacyExternalStorage="true" in the manifest also.
Then for opening the gallery use this code:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction("android.intent.action.PICK");
startActivityForResult(intent, PICK_IMAGE_REQUEST);
In onActivityResult :
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
mImageUri = data.getData();
//Use glide for better result
Glide.with(this).load(mImageUri).into(mImageView);
}
来源:https://stackoverflow.com/questions/65865376/why-cant-i-upload-a-picture-from-gallery-in-my-android-app-if-the-picture-was