【问题标题】:Why can't I upload a picture from gallery in my android app, if the picture was taken with the camera app from android?如果照片是使用 Android 的相机应用拍摄的,为什么我不能在我的 Android 应用中从图库中上传图片?
【发布时间】:2021-01-23 23:01:25
【问题描述】:

我想从图库上传一张图片并将其显示在我的 Android 应用上。例如,如果我从屏幕截图文件夹中选择图像,这会很好。但是,当我从存储用手机相机拍摄的照片的文件夹中选择图像时,它不起作用。

    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;
    }
}

【问题讨论】:

  • 您发布的代码中没有上传代码。你认为什么是“它不起作用”?
  • 也许上传是错误的词。我想在我的应用程序中从图库中选择图像并将其显示在 Imageview 中。图片未显示。
  • 奇怪你没有花时间编辑你的帖子。

标签: android android-studio android-layout android-fragments android-developer-api


【解决方案1】:

确保您已授予运行时从图库中选择图像的权限以及清单中的权限。

在清单中也使用 android:requestLegacyExternalStorage="true"。

然后打开画廊使用这个代码:

Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction("android.intent.action.PICK");
                    startActivityForResult(intent, PICK_IMAGE_REQUEST);

在 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);
         }

【讨论】:

  • 使用 ACTION_PICK 不需要权限和运行时权限以及请求旧版外部存储。
【解决方案2】:

在我看来,这些问题可以通过 Ucrop 等 ImagePicker 库来解决。 Ucrop Library For Android

确保您已处理运行时权限。为了更轻松地处理权限,您可以使用 Dexter Dexter

确保您在清单文件中具有外部存储读取权限。 如果您想从相机拍摄图像,您可能还需要读/写权限。

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

注意:对于 Pie 以上的 Android 版本,请将这些属性粘贴到 manifest.xml 中的应用程序标记中:

<application
        android:preserveLegacyExternalStorage="true"
        android:requestLegacyExternalStorage="true"
        ... >
...
...
</application>

【讨论】:

    猜你喜欢
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    相关资源
    最近更新 更多