Skip to content

Instantly share code, notes, and snippets.

@MikeAfc
Last active August 29, 2015 14:05
Show Gist options
  • Save MikeAfc/9ccbebba17673535819d to your computer and use it in GitHub Desktop.
Save MikeAfc/9ccbebba17673535819d to your computer and use it in GitHub Desktop.
android choose image from camera app or gallery
private Uri outputFileUri;
private final int FROM_CHOOSER = 0;
private final int FROM_CAMERA = 1;
private final int FROM_FILE = 2;
private void openImageIntent(int from) {
// Determine Uri of camera image to save.
final File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + getString(R.string.app_name)
+ File.separator);
root.mkdirs();
final String fname = "img_" + UUID.randomUUID() + ".jpg";
final File sdImageMainDirectory = new File(root, fname);
outputFileUri = Uri.fromFile(sdImageMainDirectory);
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(
captureIntent, 0);
for (ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName,
res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
if (from == FROM_CHOOSER) {
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent,
"Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
cameraIntents.toArray(new Parcelable[] {}));
startActivityForResult(chooserIntent, 101);
} else if (from == FROM_CAMERA) {
final Intent cameraIntent = Intent.createChooser(
cameraIntents.remove(0), "Select Source");
cameraIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
cameraIntents.toArray(new Parcelable[] {}));
startActivityForResult(cameraIntent, 101);
} else if (from == FROM_FILE) {
startActivityForResult(galleryIntent, 101);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 101) {
final boolean isCamera;
if (data == null) {
isCamera = true;
} else {
isCamera = MediaStore.ACTION_IMAGE_CAPTURE.equals(data
.getAction());
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
} else {
selectedImageUri = data == null ? null : data.getData();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment