android 10,从图库中选择一张照片

vcirk6k6  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(333)

人。我想从安卓10图库里弄张照片。但是,它告诉我bitmap=null,下面的代码,怎么了?

public void createIntent() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
    }
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
            uri = data.getData();
if(Build.VERSION.SDK_INT < 29  ) {
                    this.bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                } else {
                    this.bitmap = ImageDecoder.decodeBitmap(ImageDecoder.createSource(this.getContentResolver(), uri));
                }
i5desfxk

i5desfxk1#

这对我来说也适用于android10。

protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    String imagePath =  getPath(data.getData());
    BitmapFactory.Options options = new BitmapFactory.Options();
    Bitmap bitmap = null;
    try {
        bitmap = BitmapFactory.decodeStream(new FileInputStream(imagePath),
                null, options);
    } catch (FileNotFoundException e) {
        logger.log(Level.SEVERE, "Error loading the bitmap from the path: "
                + imagePath, e);
    }
  }

 private String getPath(Uri uri) {

    String path = "";
    Cursor cursor = null;
    try {
        String[] projection = { MediaColumns.DATA };
        cursor = getContentResolver().query(uri, projection, null, null,
                null);
        if (cursor == null || !cursor.moveToFirst()) {
            path = "";
        } else {
            int columnIndex = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
            path = cursor.getString(columnIndex);
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return path;
}
sxpgvts3

sxpgvts32#

我已经创造了解决方案。

protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
         uri = data.getData();
        InputStream stream = this.getContentResolver().openInputStream(uri);
        bitmap = BitmapFactory.decodeStream(stream);

}

此代码适用于build.version.sdk\ u int<29和build.version.sdk\ u int>=29

相关问题