I have an intent chooser that allows me to pick image from gallery or camera like this:
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT,null);
galleryIntent.setType("image/*");
galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Intent chooser = new Intent(Intent.ACTION_CHOOSER);
chooser.putExtra(Intent.EXTRA_INTENT, galleryIntent);
chooser.putExtra(Intent.EXTRA_TITLE, "title");
Intent[] intentArray = {cameraIntent};
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooser,REQUEST_CODE);
I want my onActivityResult method to be like this:
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(Condition == picture_coming_from_gallery)
{
//my code here
}
else if(condition == picture_coming_from_camera)
{
//another code here
}
}
What is the condition that allows me to know which source my image is coming from?
Updated:
Now it's working and here is the solution:
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
{
if(data.getData()!=null)
{
try
{
if (bitmap != null)
{
bitmap.recycle();
}
InputStream stream = getContentResolver().openInputStream(data.getData());
bitmap = BitmapFactory.decodeStream(stream);
stream.close();
imageView.setImageBitmap(bitmap);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
{
bitmap=(Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(bitmap);
}
super.onActivityResult(requestCode, resultCode, data);
}
}
Thank you for you help!
Although the current piece of code is a neat way of presenting options to choose from, I found that it was severely difficult to manage. At least in my use case it was. I need to store images taken off the Camera to process further in the Aviary SDK (if the user so chooses).
To that end, I would like to propose a workaround.
This does not address your question per se. But offers an alternative considering you need to know where the Image is coming from (Camera / Gallery).
AlertDialog.Builder builder = new AlertDialog.Builder(StatusUpdate.this);
builder.setTitle("Choose Image Source");
builder.setItems(new CharSequence[] {"Gallery", "Camera"},
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
// GET IMAGE FROM THE GALLERY
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
Intent chooser = Intent.createChooser(intent, "Choose a Picture");
startActivityForResult(chooser, ACTION_REQUEST_GALLERY);
break;
case 1:
Intent getCameraImage = new Intent("android.media.action.IMAGE_CAPTURE");
File cameraFolder;
if (android.os.Environment.getExternalStorageState().equals
(android.os.Environment.MEDIA_MOUNTED))
cameraFolder = new File(android.os.Environment.getExternalStorageDirectory(),
"some_directory_to_save_images/");
else
cameraFolder= StatusUpdate.this.getCacheDir();
if(!cameraFolder.exists())
cameraFolder.mkdirs();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
String timeStamp = dateFormat.format(new Date());
String imageFileName = "picture_" + timeStamp + ".jpg";
File photo = new File(Environment.getExternalStorageDirectory(),
"some_directory_to_save_images/" + imageFileName);
getCameraImage.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
initialURI = Uri.fromFile(photo);
startActivityForResult(getCameraImage, ACTION_REQUEST_CAMERA);
break;
default:
break;
}
}
});
builder.show();
This is the result (I still maintain that you code gives a much better selection set, but again, not the simplest thing in your use case or in mine either):
Now you can process the result based on the source of the selection:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case ACTION_REQUEST_GALLERY:
break;
case ACTION_REQUEST_CAMERA:
break;
}
}
};
UPDATED:
Found it!! There is an answer here on SO that addresses exactly what you need. It is still a * workaround of sorts*. In the sense that it does not rely on different requestCodes. But works nonetheless.
Strange I missed it when I was stuck with this. :-(
NOTE: I am not posting the code here and am linking to it instead. All props go to the original author. :-)
You can distinguish by using REQUEST_CODE
private static final int PICK_FROM_CAMERA = 1;
private static final int PICK_FROM_GALLARY = 2;
/* For Image capture from camera */
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, PICK_FROM_CAMERA);
/* For Image capture from Gallary*/
startActivityForResult(new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI),
PICK_FROM_GALLARY);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case PICK_FROM_CAMERA:
if (resultCode == Activity.RESULT_OK) {
Bitmap bitmapImage = (Bitmap) intent.getExtras().get("data");
}
break;
case PICK_FROM_GALLARY:
if (resultCode == Activity.RESULT_OK) {
Uri mImageCaptureUri = intent.getData();
}
break;
}
}
Related
I want to select image from gallery and crop it with 800*600 size, but with sizes larger than 500*500 it is not working!! how can I do it?
my code is as below:
public void showFileChooser() {
Intent imageDownload = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
imageDownload.putExtra("crop", "true");
imageDownload.putExtra("aspectX", 4);
imageDownload.putExtra("aspectY", 3);
imageDownload.putExtra("outputX", 800);
imageDownload.putExtra("outputY", 600);
imageDownload.putExtra("return-data", true);
startActivityForResult(imageDownload, 2);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2 && resultCode == RESULT_OK && null != data) {
Bundle extras = data.getExtras();
bitmap1 = extras.getParcelable("data");
imageView1.setImageBitmap(bitmap1);
}
}
Try this, it works for me, Hope it'll help you too....
1 - Choose image from gallery
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select File"),Util.REQUEST_GALLERY);
2 - Crop image in onActivityResult as below
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == getActivity().RESULT_OK) {
switch (requestCode) {
case Util.REQUEST_GALLERY:
try {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && !Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED_READ_ONLY)) {
File file = new File(Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator+ ".MyImages"+ File.separator+ "picture").getPath());
if (!file.exists()) {
file.mkdirs();
}
selectedPath1 = File.createTempFile("myImages"+ new SimpleDateFormat("ddMMyyHHmmss",Locale.US).format(new Date()),".jpg", file).toString();
croppedImageUri = Uri.fromFile(new File(selectedPath1));
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(data.getData(), "image/*");
intent.putExtra("outputX", 700); // pass width
intent.putExtra("outputY", 700); // pass height
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("noFaceDetection", true);
intent.putExtra("output", croppedImageUri);
startActivityForResult(intent, Util.REQUEST_CROP_IMAGE);
} else {
Toast.show(getActivity(), "Please insert memory card to take pictures and make sure it is writeable");
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case Util.REQUEST_CROP_IMAGE:
Logg.e(getClass().getSimpleName(), "Profile_Pic ===== " + selectedPath1);
imgProfile.setImageURI(Uri.parse("file://" + croppedImageUri));
break;
default:
break;
}
}
}
Simple question. Is it possible to allow a button (preferably a FAB) to open a camera app, sort of as a short cut? This shortcut can either lead to the default camera, or lead to any downloaded camera apps.
Yes, it's possible.
You can create an implicit intent with action ACTION_IMAGE_CAPTURE.
eg:
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
String imgPath = file.getAbsolutePath();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE);
To handle the result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == CAPTURE_IMAGE) {
Bitmap resultAsBitmap = BitmapFactory.decodeFile(imgPath);
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
PS: Don't forget to add your permissions in manifest file.
i have a radio button. when i click on radio button camera intent is opened after taking a image using camera. image is not updating to image view.
i have used all permissions in my manifest file.
RB_PhotoStatus
.setOnCheckedChangeListener(new android.widget.RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group,
int checkedId) {
switch (checkedId) {
case R.id.yes:
//photoCollected = "Yes";
// create intent with ACTION_IMAGE_CAPTURE action
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
break;
case R.id.no:
photoCollected = "No";
break;
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bp = (Bitmap) data.getExtras().get("data");
imageView1.setImageBitmap(bp);
}
Taking Photos Simply!
This answer explains how to capture photos using an existing camera application.
<manifest ... >
<uses-feature android:name="android.hardware.camera"
android:required="true" />
...
</manifest>
Request for camera application.
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
Camera return intent with data on Activity override function onActivityResult as bellow:-
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}
}
For more info follows this link given bellow:
http://developer.android.com/training/camera/photobasics.html
It doesn't work because Camera Intent won't return the entire BitMap, but only the reference (Uri) to the created file.
Uri selectedImage = data.getData();
From this Uri you may re-load the BitMap using BitmapFactory.decodeFile
On radiobuttonclick();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
onActivityResult();
Uri originalUri = data.getData();
imageview.setImageURI(originalUri);
And If you want to get bitmap then
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), originalUri);
private String mCurrentPhotoPath;
final String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
final File image = create_directory();
// Save a file: path for use with ACTION_VIEW intents
try {
mCurrentPhotoPath = image.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
final Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
if (image != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
} else {
snackbar = Snackbar.make(findViewById(android.R.id.content), "An error has occurred", Snackbar.LENGTH_SHORT);
snackbar.setAction("Dismiss", clickListener);
snackbar.show();
}
}
}
public File create_directory() {
// Create an image file name
final String imageFileName;
final String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(new Date());
final String user_id = "1_";
imageFileName = user_id + timeStamp + "_";
final String proj_name = "test";
final String folder_timeStamp = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH).format(new Date());
final String path = "/TEST/" + proj_name + "/" + folder_timeStamp;
final File dr = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), path);
if (!dr.exists()) {
dr.mkdirs();
}
File image = null;
try {
image = File.createTempFile(imageFileName, ".jpg", dr);
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
if (resultCode == RESULT_OK){
//do something with the image which is stored in mCurrentPhotoPath
}
}
}
I'm trying to implement SoundCloud's image crop to my app. Here's what I'm doing so far:
call Crop.pickImage((Activity) this) to pick an image
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Crop.REQUEST_PICK && resultCode == RESULT_OK) {
Uri inputUri = data.getData();
new Crop(inputUri).output(outputUri).asSquare().start((Activity) context);
}
else if (requestCode == Crop.REQUEST_CROP && resultCode == RESULT_OK) {
Uri cropped = data.getData();
}
}
At this point I don't know what should be the outputUri. I can just use the same inputUri as the output, but that would overwrite the original image file. I want to create a new file instead. But I can't create new Uri since Android Studio tells me the newly initialized Uri is abstract and can't be used.
I used following methods for my cropping image library for URI creation as well. Hopefully it will helps you:
private void fileSaving(){
String stateEnvironment = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(stateEnvironment)) {
mFileTemp = ChatUtils.getOutputMediaFile(101);//new File(Environment.getExternalStorageDirectory(), TEMP_PHOTO_FILE_NAME);
} else {
mFileTemp = new File(getFilesDir(), sTEMP_PHOTO_FILE_NAME);
}
}
private void takePicture() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
Uri mImageCaptureUri = null;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mImageCaptureUri = Uri.fromFile(mFileTemp);
} else {
// mImageCaptureUri =
// InternalStorageContentProvider.CONTENT_URI;
}
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent, mREQUEST_CODE_TAKE_PICTURE);
} catch (ActivityNotFoundException e) {
}
}
I have already selected an image from SD card in my activity's ImageView using Intent.and now I want to show a fixed size moving Rectangle i.e. we have to use gesture and whatever portion of the image we want,then we are able to crop that.How can we do that?Its really tough for me to do?
Please help me in doing that?
Update-->I have been able to bring the rectangle and I m getting problem in cropping and saving that selected part.How to do this?
ok geetanjali. try this code this will open gallery and you can pick a photo to crop, it will store with name starts from apple, you can see cropped image in your activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("crop","true");
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempFile());
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, 1);
}
private Uri getTempFile() {
if (isSDCARDMounted()) {
String f;
muri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"apple_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
//File f = new File(Environment.getExternalStorageDirectory(),"titus1.jpg");
try {
f=muri.getPath();
} catch (Exception e) {
}
return muri;
} else {
return null;
}
}
private boolean isSDCARDMounted(){
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED))
return true;
return false;
}
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
String filePath= muri.getPath();
Log.e("path", "filePath");
Toast.makeText(this, filePath, Toast.LENGTH_LONG).show();
Bitmap selectedImage = BitmapFactory.decodeFile(filePath);
image = (ImageView)findViewById(R.id.image);
image.setImageBitmap(selectedImage);
}
}
}