简体   繁体   中英

How to get Bitmap from MediaStore.Images.Media.getBitmap(contentResolver, uri)?

I am having difficulties with retrieving a bitmap from my uri. I am trying to fetch the image taken from camera after opening the camera via an Intent.

                    try {
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            imageUri = FileProvider.getUriForFile(mContext, mContext.getApplicationContext().getPackageName(), createImageFile());
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);   // set the image file name
                        }
                        startActivityForResult(intent, PERMISSION_REQUEST_CODE_CAMERA);
                    } catch (ActivityNotFoundException e) {
                        e.printStackTrace();
                    }

The imageUri when logged is

content://com.example/external_files/Pictures/CustomFolder/15122017_photo_115344.jpg

After the camera is opened and the picture taken, my onActivityResult is called. Because I use MediaStore.EXTRA_OUTPUT I do not receive anything in my data object it is null. I try to use MediaStore.Images.Media.getBitmap() to retrieve the bitmap. I pass in the imageUri. I believe this may be incorrect because I receive an exception.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PERMISSION_REQUEST_CODE_CAMERA) {
        if (resultCode == Activity.RESULT_OK) {

            Bitmap bitmap;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), imageUri);
                ivProfilePhoto.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        } else if (resultCode == Activity.RESULT_CANCELED){

        }
    }

The exception I receive is

java.io.FileNotFoundException: No such file or directory

EDIT:

I can hang on to the File, but this does not seem to work either. Here is what I have tried. I updated my intent to be the following

                    try {
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            mFile = createImageFile();
                            imageUri = FileProvider.getUriForFile(mContext, mContext.getApplicationContext().getPackageName(), mFile);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);   // set the image file name
                        }
                        startActivityForResult(intent, PERMISSION_REQUEST_CODE_CAMERA);
                    } catch (ActivityNotFoundException e) {
                        e.printStackTrace();
                    }

Then in onActivityResult, I do the following

            Bitmap bitmap = BitmapFactory.decodeFile(mFile.getPath());
            ivProfilePhoto.setImageBitmap(bitmap);

Nothing gets set for the image. Also, for your FYI this is how I am creating my directory and setting my file image name.

private File createImageFile() {
    File imgFileDir = getDir();
    if (!imgFileDir.exists() && !imgFileDir.mkdirs()) {
        Logger.e(TAG, "Directory does not exist");
        imgFileDir.mkdirs();
    }
    Logger.e("TEST", "imgFileDir= " + imgFileDir);
    // Locale.US to get local formatting
    SimpleDateFormat timeFormat = new SimpleDateFormat("hhmmss", Locale.US);
    SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyyy", Locale.US);
    String time = timeFormat.format(new Date());
    String date = dateFormat.format(new Date());
    String photoFile = date + "_photo_" + time + ".jpg";
    filename = imgFileDir.getPath() + File.separator + photoFile;

    Logger.i(TAG, "time(hhmmss): " + time + " date(ddmmyyyy): " + date + "\nfilename: "
            + filename + " photoFile: " + photoFile);
    return new File(filename);
}

private File getDir() {
    File sdDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    return new File(sdDir, "CustomFolder");
}

Ideally, switch to using an image-loading library (eg, Glide, Picasso), so that your I/O and bitmap processing can be performed on a background thread.

Beyond that, hold onto the File object, not the Uri , and load the image using the File (eg, BitmapFactory.decodeFile() ). This will be faster, as there will be no ContentProvider overhead.

这对我有用

val bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);

As per my understanding you want to fetch the uri from the bitmap so considerably this code works perfactably fine :-

 public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
}

ADD this

public void onClick(View v) {   
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, 1);
}

when you will replace your code with this above code then automatically your this

public void onActivityResult(int requestCode, int resultCode,
@Nullable Intent data){}

Method will Start working

//No Need to write this code in onclick method
    Intent intent=new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT)
    startActivityForResult(intent,1);
    Toast.makeText(getContext(), "image"+intent, Toast.LENGTH_SHORT).show();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM