Search code examples
androidandroid-cameraandroid-image

How to capture image thumbnail AND save file in a custom folder in Android


I am trying to capture an image from an existing camera application, save the image in a customized folder, and display the thumbnail in and imageView. The camera supplies the thumbnail as long as I haven't specified where to save the file:

I can get the thumbnail from the returned intent:

...
  Intent i = = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  startActivityForResult(i)
}

protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
  super.onActivityResult(requestCode, resultCode, intent);      
  Bundle extras = intent.getExtras();
  Bitmap mImageBitmap = (Bitmap) extras.get("data");
}

Or I can save the file in a specified folder (which works fine)

  ...
  Intent i = = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  i.putExtra((MediaStore.EXTRA_OUTPUT, outputFileUri);
  startActivityForResult(i)
}

but the thumbnail is no longer stored in the intent extra "data", and when I try to retrieve the thumbnail, I get an error (this is from my LogCat)

10-04 06:30:14.463: E/AndroidRuntime(1967): Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity: java.lang.NullPointerException

As you can see, the field returned is null instead of the bitmap thumbnail. I have tried decoding the bitmap afterwards to generate a thumbnail from the file directly, but it takes too long (even when downsampled I get out of memory error) , and it seems counterintuitive to do the job twice. Any suggestions?


Solution

  • Okay. If you are passing an outputURI to the intent then you will not be able to receive the data back from the intent in onActivityResult().

    I think only option is to use the same outputURI to display the thumbnail..

    Try this.

    void captureImage(){
        File file = new File(Environment.getExternalStorageDirectory()
        .getAbsolutePath() + "/MyFolder", "myImage"+ ".jpg");
    
        mCapturedImagePath = file.getAbsolutePath();
        Uri outputFileUri = Uri.fromFile(file);
        Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        i.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
        startActivityForResult(i, CAMERA_REQUEST);
    }
    
    onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERA_REQUEST) {
            if (resultCode == RESULT_OK) {
                File file = new File(mCapturedImagePath);
                imageView.setImageURI(Uri.fromFile(file));
            }
        }
    }