当前位置: 首页 > 知识库问答 >
问题:

BitmapFactory:无法解码流:React Native的java.io.FileNotFoundException

鞠征
2023-03-14
    compileSdkVersion 27
    buildToolsVersion "27.0.3"

    configurations {
        all*.exclude group: 'com.android.support', module: 'support-v4'
        all*.exclude group: 'com.android.support', module: 'support-annotations'
        compile.exclude group: "org.apache.httpcomponents", module: "httpclient"
    }


    defaultConfig {
        applicationId "com.myapp"
        minSdkVersion 16
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

        ndk {
            abiFilters "armeabi-v7a", "x86"
        }


    dexOptions {
    javaMaxHeapSize "4g"
    preDexLibraries = false
    incremental true
}

compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "com.github.hotchemi:permissionsdispatcher:4.0.0-alpha1"
    annotationProcessor "com.github.hotchemi:permissionsdispatcher-processor:4.0.0-alpha1"

    implementation 'com.android.support:support-v13:27+'
    implementation 'com.android.support:appcompat-v7:27+'
    implementation "com.facebook.react:react-native:+"  // From node_modules

}
    private static final int PICK_FROM_GALLERY = 1;

ChoosePhoto.setOnClickListener(new View.OnClickListener()
{
    @Override
    public void onClick (View v){
    try {
        if (ActivityCompat.checkSelfPermission(EditProfileActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(EditProfileActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PICK_FROM_GALLERY);
        } else {
            Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(galleryIntent, PICK_FROM_GALLERY);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
  }
});


@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults)
    {
       switch (requestCode) {
            case PICK_FROM_GALLERY:
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                  Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                  startActivityForResult(galleryIntent, PICK_FROM_GALLERY);
                } else {
                    //do something like displaying a message that he didn`t allow the app to access gallery and you wont be able to let him select from gallery
                }
                break;
        }
    }

堆栈跟踪:

    07-22 17:59:03.978  8497  8497 D ViewRootImpl@39eadf9[UCropActivity]: MSG_WINDOW_FOCUS_CHANGED 0
07-22 17:59:03.992  8497  8497 E BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/DCIM/IMMQY/IMG_20180722175858_942.jpg (No such file or directory)
07-22 17:59:03.996  8497  8497 W System.err: java.lang.Exception: Invalid image selected

本机代码:

    componentDidMount(){
async function requestCameraPermission() {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.CAMERA,
      {
        'title': 'Cool Photo App Camera Permission',
        'message': 'Cool Photo App needs access to your camera ' +
                   'so you can take awesome pictures.'
      }
    )
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log("You can use the camera")
    } else {
      console.log("Camera permission denied")
    }
  } catch (err) {
    console.warn(err)
  }
}
}

共有1个答案

颛孙铭
2023-03-14

有两件事。您需要在清单中为外部读取存储添加权限,然后在您能够使用它之后,如果您使用的是23以上的api,那么您必须使用Easy permission。

写:

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

改为:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 private String[] galleryPermissions = {Manifest.permission.READ_EXTERNAL_STORAGE, 
 Manifest.permission.WRITE_EXTERNAL_STORAGE};

 if (EasyPermissions.hasPermissions(this, galleryPermissions)) {
        pickImageFromGallery();
    } else {
        EasyPermissions.requestPermissions(this, "Access for storage",
                101, galleryPermissions);
    }
 @Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
 if (resultCode == RESULT_OK && requestCode == 1 && null != data) {
    decodeUri(data.getData());
 }
  }

   public void decodeUri(Uri uri) {
   ParcelFileDescriptor parcelFD = null;
    try {
    parcelFD = getContentResolver().openFileDescriptor(uri, "r");
    FileDescriptor imageSource = parcelFD.getFileDescriptor();

    // Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFileDescriptor(imageSource, null, o);

    // the new size we want to scale to
    final int REQUIRED_SIZE = 1024;

    // Find the correct scale value. It should be the power of 2.
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) {
        if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) {
            break;
        }
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }

    // decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    Bitmap bitmap = BitmapFactory.decodeFileDescriptor(imageSource, null, o2);

    imageview.setImageBitmap(bitmap);

   } catch (FileNotFoundException e) {
    // handle errors
   } catch (IOException e) {
    // handle errors
    } finally {
    if (parcelFD != null)
        try {
            parcelFD.close();
        } catch (IOException e) {
            // ignored
        }
     }
           }
 类似资料:
  • 问题内容: 嘿,我不确定为什么每次选择图库中的图像时都会出现这种情况吗? 这是代码: 错误: 问题答案: 不要假设有文件路径。Android 4.4及更高版本即将删除它们。而且您获得的uri已经没有路径。 您仍然可以通过()或文件描述符访问文件内容。 在这里进行了解释:ContentProviders:打开一个文档(向下滚动,指向该节的链接似乎已损坏) 而且确实适用于较旧的android版本。

  • 如何解决它。请帮助我。提前谢谢。

  • 我有一个定义权限的文件。该代码适用于较低版本的android,但8.0及更高版本不适用。所以我明确地要求进行自我许可检查。这段代码昨天还在工作,但突然我再次获得了相同的权限拒绝错误。

  • 我正试图从我的数据库联机获取图片,在我的“ImageLink”中,这是我表中的datafield,我把我上传的图片的url放在那里,但不幸的是,它给了我这个错误。 以下是我在OnPostExecute中的代码:

  • 问题内容: 我试图在线从数据库中的表中的数据字段“ imagelink”中获取图片,我将上传的图片的网址放在此处,但不幸的是,它给了我这个错误。 这是我在onPostExecute中的代码: 问题答案: 使用代替。

  • 问题内容: 我正在创建一个简单的应用程序拍照。这是我的代码 如您所见,我已经在末尾和logcat中(以及)中添加了此错误代码: 猜猜该目录是否存在? spoler警报 ,确实如此。而且它不像是在之后创建图片。我真的不明白我在做什么错。一切正常,除非实际上必须显示照片,然后才不显示照片。只是空白。就像WTF M8一样,我只是想尽我所能,而不必发疯。 问题答案: 替换为。 需要一个路径,而不是uri字