Tuesday, April 7, 2015

Android : Android camera API not getting image from file path



I'm trying to take a picture with an Android device, and I'm running into an issue when I'm trying to create a Bitmap from the file path. I'm basing my implementation directly off of Android's docs.


Note that I had to make mCurrentPhotoPath to be static for the variable to be not null in the onActivityResult method.


I have the following line in my AndroidManifest.xml:



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


Below is the code:



static final int REQUEST_TAKE_PHOTO = 1;

private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}

static String mCurrentPhotoPath;

private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);

// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, options);
photoButton.setImageBitmap(bitmap);
}
}


The issue is, in the onActivityResult method, the line



Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, options);


The result is bitmap = null. I can't figure what I'm doing wrong. Does anyone know?


No comments:

Post a Comment