How to get Bitmap from an Uri?

前端 未结 16 1137
时光说笑
时光说笑 2020-11-22 10:41

How to get a Bitmap object from an Uri (if I succeed to store it in /data/data/MYFOLDER/myimage.png or file///data/data/MYFOLDER/myimage.png) to u

相关标签:
16条回答
  • 2020-11-22 10:44

    It seems that MediaStore.Images.Media.getBitmap was deprecated in API 29. The recommended way is to use ImageDecoder.createSource which was added in API 28.

    Here's how getting the bitmap would be done:

    val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        ImageDecoder.decodeBitmap(ImageDecoder.createSource(requireContext().contentResolver, imageUri))
    } else {
        MediaStore.Images.Media.getBitmap(requireContext().contentResolver, imageUri)
    }
    
    0 讨论(0)
  • 2020-11-22 10:45
    private void uriToBitmap(Uri selectedFileUri) {
        try {
            ParcelFileDescriptor parcelFileDescriptor =
                    getContentResolver().openFileDescriptor(selectedFileUri, "r");
            FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
            Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
    
            parcelFileDescriptor.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 10:47

    This is the easiest solution:

    Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
    
    0 讨论(0)
  • 2020-11-22 10:47

    (KOTLIN) So, as of April 7th, 2020 none of the above mentioned options worked, but here's what worked for me:

    1. If you want to store the bitmap in a val and set an imageView with it, use this:

      val bitmap = BitmapFactory.decodeFile(currentPhotoPath).also { bitmap -> imageView.setImageBitmap(bitmap) }

    2. If you just want to set the bitmap to and imageView, use this:

      BitmapFactory.decodeFile(currentPhotoPath).also { bitmap -> imageView.setImageBitmap(bitmap) }

    0 讨论(0)
  • 2020-11-22 10:48
    Uri imgUri = data.getData();
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imgUri);
    
    0 讨论(0)
  • 2020-11-22 10:49

    you can do this structure:

    protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
        switch(requestCode) {
            case 0:
                if(resultCode == RESULT_OK){
                        Uri selectedImage = imageReturnedIntent.getData();
                        Bundle extras = imageReturnedIntent.getExtras();
                        bitmap = extras.getParcelable("data");
                }
                break;
       }
    

    by this you can easily convert a uri to bitmap. hope help u.

    0 讨论(0)
提交回复
热议问题