If I want to capture image from native camera, I can do:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, IMAGE_CAPTURE);
If I want to get image from gallery, I can do:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
I am wondering how can put the above two together.
That means GET IMAGE FROM GALLERY OR CAPTURE PHOTO
Is there any example code to do it?
Thanks.
If you want to take picture from Camera or Gallery Intent Together, Then check below link. Same question also posted here.
Capturing image from gallery & camera in android
UPDATED CODE:
check below code, In this code not same as you want into listview, but it gives the option in the dialogBox choose image from Gallary OR Camera.
public class UploadImageActivity extends Activity {
ImageView img_logo;
protected static final int CAMERA_REQUEST = 0;
protected static final int GALLERY_PICTURE = 1;
private Intent pictureActionIntent = null;
Bitmap bitmap;
String selectedImagePath;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
img_logo= (ImageView) findViewById(R.id.imageView1);
img_logo.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startDialog();
}
});
}
private void startDialog() {
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(
getActivity());
myAlertDialog.setTitle("Upload Pictures Option");
myAlertDialog.setMessage("How do you want to set your picture?");
myAlertDialog.setPositiveButton("Gallery",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Intent pictureActionIntent = null;
pictureActionIntent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(
pictureActionIntent,
GALLERY_PICTURE);
}
});
myAlertDialog.setNegativeButton("Camera",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(f));
startActivityForResult(intent,
CAMERA_REQUEST);
}
});
myAlertDialog.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
bitmap = null;
selectedImagePath = null;
if (resultCode == RESULT_OK && requestCode == CAMERA_REQUEST) {
File f = new File(Environment.getExternalStorageDirectory()
.toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
if (!f.exists()) {
Toast.makeText(getBaseContext(),
"Error while capturing image", Toast.LENGTH_LONG)
.show();
return;
}
try {
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
bitmap = Bitmap.createScaledBitmap(bitmap, 400, 400, true);
int rotate = 0;
try {
ExifInterface exif = new ExifInterface(f.getAbsolutePath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
} catch (Exception e) {
e.printStackTrace();
}
Matrix matrix = new Matrix();
matrix.postRotate(rotate);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);
img_logo.setImageBitmap(bitmap);
//storeImageTosdCard(bitmap);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (resultCode == RESULT_OK && requestCode == GALLERY_PICTURE) {
if (data != null) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage, filePath,
null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
selectedImagePath = c.getString(columnIndex);
c.close();
if (selectedImagePath != null) {
txt_image_path.setText(selectedImagePath);
}
bitmap = BitmapFactory.decodeFile(selectedImagePath); // load
// preview image
bitmap = Bitmap.createScaledBitmap(bitmap, 400, 400, false);
img_logo.setImageBitmap(bitmap);
} else {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
}
}
}
Also add pemission:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature
android:name="android.hardware.camera.autofocus"
android:required="false" />
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
store Image to sdcard:
private void storeImageTosdCard(Bitmap processedBitmap) {
try {
// TODO Auto-generated method stub
OutputStream output;
// Find the SD Card path
File filepath = Environment.getExternalStorageDirectory();
// Create a new folder in SD Card
File dir = new File(filepath.getAbsolutePath() + "/appName/");
dir.mkdirs();
String imge_name = "appName" + System.currentTimeMillis()
+ ".jpg";
// Create a name for the saved image
File file = new File(dir, imge_name);
if (file.exists()) {
file.delete();
file.createNewFile();
} else {
file.createNewFile();
}
try {
output = new FileOutputStream(file);
// Compress into png format image from 0% - 100%
processedBitmap
.compress(Bitmap.CompressFormat.PNG, 100, output);
output.flush();
output.close();
int file_size = Integer
.parseInt(String.valueOf(file.length() / 1024));
System.out.println("size ===>>> " + file_size);
System.out.println("file.length() ===>>> " + file.length());
selectedImagePath = file.getAbsolutePath();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Let's say that you have two intents. One that would open a camera, one that would open a gallery. I will call these cameraIntent and gallerIntent in the example code. You can use intent chooser to combine these two:
Kotlin:
val chooser = Intent.createChooser(galleryIntent, "Some text here")
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, arrayOf(cameraIntent))
startActivityForResult(chooser, requestCode)
Java:
Intent chooser = Intent.createChooser(galleryIntent, "Some text here");
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { cameraIntent });
startActivityForResult(chooser, requestCode);
This is, as you asked, how you can put the two together (without having to make your own UI/ dialog).
If you want to show all the apps installed in the phone that can deal with photos such as Camera, Gallery, Dropbox, etc.
You can do something like:
1.- Ask for all the intents available:
Intent camIntent = new Intent("android.media.action.IMAGE_CAPTURE");
Intent gallIntent=new Intent(Intent.ACTION_GET_CONTENT);
gallIntent.setType("image/*");
// look for available intents
List<ResolveInfo> info=new ArrayList<ResolveInfo>();
List<Intent> yourIntentsList = new ArrayList<Intent>();
PackageManager packageManager = context.getPackageManager();
List<ResolveInfo> listCam = packageManager.queryIntentActivities(camIntent, 0);
for (ResolveInfo res : listCam) {
final Intent finalIntent = new Intent(camIntent);
finalIntent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
yourIntentsList.add(finalIntent);
info.add(res);
}
List<ResolveInfo> listGall = packageManager.queryIntentActivities(gallIntent, 0);
for (ResolveInfo res : listGall) {
final Intent finalIntent = new Intent(gallIntent);
finalIntent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
yourIntentsList.add(finalIntent);
info.add(res);
}
2.- Show a custom dialog with the list of items:
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle(context.getResources().getString(R.string.select_an_action));
dialog.setAdapter(buildAdapter(context, activitiesInfo),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Intent intent = intents.get(id);
context.startActivityForResult(intent,1);
}
});
dialog.setNeutralButton(context.getResources().getString(R.string.cancel),
new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
This is a full example: https://gist.github.com/felixgborrego/7943560
In fact your dialog title is "select an action" means the dialog is a Intent chooser actually. not a user customed dialog. The every single item presents a Intent.
public void click(View view) {
File file = getExternalFilesDir(Environment.DIRECTORY_DCIM);
Uri cameraOutputUri = Uri.fromFile(file);
Intent intent = getPickIntent(cameraOutputUri);
startActivityForResult(intent, -1);
}
private Intent getPickIntent(Uri cameraOutputUri) {
final List<Intent> intents = new ArrayList<Intent>();
if (true) {
intents.add(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI));
}
if (true) {
setCameraIntents(intents, cameraOutputUri);
}
if (intents.isEmpty()) return null;
Intent result = Intent.createChooser(intents.remove(0), null);
if (!intents.isEmpty()) {
result.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents.toArray(new Parcelable[] {}));
}
return result;
}
private void setCameraIntents(List<Intent> cameraIntents, Uri output) {
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, output);
cameraIntents.add(intent);
}
}
You may need solve permissions by yourself if run on OS >= 23
Here's my demo:(Appearance differences since OS different)
I think I encountered your case before. An idea is that we will create a one item list alert dialog with selectable item, and each item will do a unique function defined by your own intention. If you want an icon for each element in items list, it should take a bit more work to do. Hope it will helpful.
String title = "Open Photo";
CharSequence[] itemlist ={"Take a Photo",
"Pick from Gallery",
"Open from File"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.icon_app);
builder.setTitle(title);
builder.setItems(itemlist, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:// Take Photo
// Do Take Photo task here
break;
case 1:// Choose Existing Photo
// Do Pick Photo task here
break;
case 2:// Choose Existing File
// Do Pick file here
break;
default:
break;
}
}
});
AlertDialog alert = builder.create();
alert.setCancelable(true);
alert.show();
Create a button in your XML layout and the add the attribute android:onClick="takeAPicture"
then in your main activity create a method with the same name from the onClick attribute.
public void takeAPicture(View view){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, IMAGE_CAPTURE);
}
And just do another method for when you want to get the image from the gallery:
public void getImageFromGallery(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
public static Intent getPickImageIntent(Context context) {
Intent chooserIntent = null;
List<Intent> intentList = new ArrayList<>();
Intent pickIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePhotoIntent.putExtra("return-data", true);
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(context)));
intentList = addIntentsToList(context, intentList, pickIntent);
intentList = addIntentsToList(context, intentList, takePhotoIntent);
if (intentList.size() > 0) {
chooserIntent = Intent.createChooser(intentList.remove(intentList.size() - 1),
context.getString(R.string.pick_image_intent_text));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentList.toArray(new Parcelable[]{}));
}
return chooserIntent;
}
private static List<Intent> addIntentsToList(Context context, List<Intent> list, Intent intent) {
List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resInfo) {
String packageName = resolveInfo.activityInfo.packageName;
Intent targetedIntent = new Intent(intent);
targetedIntent.setPackage(packageName);
list.add(targetedIntent);
}
return list;
}
Related
Using code from this answer: https://stackoverflow.com/a/12347567/734687
I use the following code to let a user submit a picture to my Android application.
private void openImageIntent() {
File outputFile = null;
try {
outputFile = File.createTempFile("tmp", "face", getCacheDir());
} catch (IOException pE) {
pE.printStackTrace();
}
mOutputFileUri = Uri.fromFile(outputFile);
// 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, mOutputFileUri);
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_PICK);
// 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[cameraIntents.size()]));
startActivityForResult(chooserIntent, 42); //XXX 42?
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 42) {
final boolean isCamera;
if (data == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri = null;
if (isCamera) {
selectedImageUri = mOutputFileUri;
} else {
selectedImageUri = data == null ? null : data.getData();
}
loadFacePicture(selectedImageUri);
}
}
}
However the Uri selectedImageUri leads to an empty file on loadFacePicture(selectedImageUri);
What did I missed ?
This is what I endup doing.
This seemed to be the source of the issue:
intent.putExtra(MediaStore.EXTRA_OUTPUT, mOutputFileUri);
The actual code:
private void openImageIntent() {
try {
outputFile = File.createTempFile("tmp", ".jpg", getCacheDir());
} catch (IOException pE) {
pE.printStackTrace();
}
mOutputFileUri = Uri.fromFile(outputFile);
// 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);
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_PICK);
// 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[cameraIntents.size()]));
startActivityForResult(chooserIntent, 42);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 42) {
Bitmap bmp = null;
if (data.hasExtra("data")) {
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
} else {
AssetFileDescriptor fd = null;
try {
fd = getContentResolver().openAssetFileDescriptor(data.getData(), "r");
} catch (FileNotFoundException pE) {
pE.printStackTrace();
}
bmp = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor());
}
try {
FileOutputStream out = new FileOutputStream(new File(mOutputFileUri.getPath()));
bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
loadFacePicture(mOutputFileUri);
}
}
}
Problem: The user may take/select up to 3 photos. I'm having trouble in figuring out how to fill the 3 cases; I'm not sure how I could do to retrieve the corresponding ImageView ID.
I tried the putextra since I'm using
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE), but it seems that it's not possible to use the putextra method (I don't retrieve any extra)
So let me share the code with you and feel free to let me know if you would proceed differently. Thanks a lot!
So here I'm catching the click event and passing the V.getID to the method that will handle the actions related to selecting/taking photos.
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.add_item_give_button:
checkAddedItem();
break;
case R.id.add_item_image_1:
selectImage(v.getId());
break;
case R.id.add_item_image_2:
selectImage(v.getId());
break;
case R.id.add_item_image_3:
selectImage(v.getId());
break;
}
}
The selectImage method is called and will handle the alertDialog that will ask if the user wants either to take a picture or to select one. I'm trying to pass the ID in the putExtra method, but nothing is received in the startActivityForResult
public void selectImage(final int imageViewID){
final CharSequence[] options = {getString(R.string.cameral_select_photo_label), getString(R.string.camera_take_photo_label), getString(R.string.common_cancel_label)};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getString(R.string.camera_dialog_title_label));
builder.setItems(options, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
#Override
public void onClick(DialogInterface dialog, int which) {
if(options[which].equals(getString(R.string.camera_take_photo_label))){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra("ImageViewID", imageViewID);
startActivityForResult(intent, REQUEST_CAMERA);
}
else if(options[which].equals(getString(R.string.cameral_select_photo_label))){
Utils.verifyStoragePermissions(getActivity());
Intent intent = new Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, getResources().getText(R.string.camera_select_image)),SELECT_FILE);
}
else if(options[which].equals(getString(R.string.common_cancel_label))){
dialog.dismiss();
}
}
});
builder.show();
}
In the startActivityForResult, I don't receive the ImageViewID. So for now, I'm just putting the image in the first ImageView since I'm not able to retrieve the right ID.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK){
if(requestCode == REQUEST_CAMERA){
Log.d("Data content", String.valueOf(data));
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
itemPic1.setImageBitmap(thumbnail);
} else if (requestCode == SELECT_FILE){
Log.d("imageViewOrigin", String.valueOf(data.getIntExtra("imageViewID", 0)));
Uri selectedImageUrl = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
CursorLoader cursorLoader = new CursorLoader(getContext(), selectedImageUrl, projection, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
Bitmap bm;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
final int REQUIRED_SIZE = 200;
int scale = 1;
while(options.outWidth / scale / 2 >= REQUIRED_SIZE && options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale += 2;
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(selectedImagePath, options);
itemPic1.setImageBitmap(bm);
}
}
}
I would recommend setting tags on the ImageViews. Follow the link, its a similar issue What is the main purpose of setTag() getTag() methods of View?. Let me know if you need more help!
Try this way :
private void openImageIntent(int IMAGE_TYPE) {
// Determine Uri of camera image to save.
final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "mycapturedImage" + File.separator);
root.mkdirs();
final String fname = getUniqueImageFilename();
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);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Choisir une Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));
startActivityForResult(chooserIntent, IMAGE_TYPE);
}
Then retrieve each Image like this :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_CANCELED) {
if (resultCode == RESULT_OK) {
if (requestCode == FIRST_IMAGE_INTENT) {
final boolean isCamera;
if (data == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
if (isCamera) {
selectedCaptureUri = outputFileUri;
} else {
selectedCaptureUri = data == null ? null : data.getData();
}
//Display image here
} else if (requestCode == SECOND_PICTURE_INTENT) {...}
I have an app with image cropping option. After cropping the actual image, the cropped image is saved in gallery. My question is how to retrieve the file name and path of the cropped image saved in gallery.
my code is,
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String [] items = new String [] {"Take from camera", "Select from gallery"};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) { //pick from camera
if (item == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else { //pick from file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
}
} );
final AlertDialog dialog = builder.create();
Button button = (Button) findViewById(R.id.btn_crop);
mImageView = (ImageView) findViewById(R.id.iv_photo);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
mImageView.setImageBitmap(photo);
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) f.delete();
break;
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size == 0) {
Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent= new Intent(intent);
co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Crop App");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
#Override
public void onCancel( DialogInterface dialog ) {
if (mImageCaptureUri != null ) {
getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
}
I have tried a lot but not retrieving the file name and path. Is there any solution.
You are using startActivityForResult(), but do you override onActivityResult()? In your case you need to do the following:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == PICK_FROM_FILE && resultCode == RESULT_OK)
{
Uri pictureUri = data.getData();
}
}
This code gets the Uri of the picture. Then you can use this Uri to get the path, using a method like below:
private String getRealPathFromURI(Context context, Uri contentUri)
{
Cursor cursor = null;
try
{
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally
{
if (cursor != null)
{
cursor.close();
}
}
}
EDIT
After you crop the Bitmap and ready to go, you can save it with something like this:
private Uri saveOutput(Bitmap croppedImage)
{
Uri saveUri = null;
// Saves the image in cache, you may want to modify this to save it to Gallery
File file = new File(getCacheDir(), "cropped");
OutputStream outputStream = null;
try
{
file.getParentFile().mkdirs();
saveUri = Uri.fromFile(file);
outputStream = getContentResolver().openOutputStream(saveUri);
if (outputStream != null)
{
croppedImage.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
}
} catch (IOException e)
{
// log the error
}
return saveUri;
}
After getting the Uri, you can get path to cropped image with the same method above.
Problem:
I am fetching image from gallery and after that cropped that image and its working perfect in all device. But it is giving me error while running in Nexus 7 kitkat since i have checked build version for it with "Gallery Stopped" error. I have implemented code and all other neccessary permission in manifest file still not getting response. So can anybody resolve this?
Here is my Code:
final String[] items = new String[] { "Take from camera",
"Select from gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.select_dialog_item, items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { // pick from
// camera
if (item == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), "tmp_avatar_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else { // pick from file
Intent intent;
if (Build.VERSION.SDK_INT < 19) {
intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_FILE);
} else {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_FILE);
}
/*
* Intent intent = new Intent();
*
* intent.setType("image/*");
* intent.setAction(Intent.ACTION_GET_CONTENT);
*
* startActivityForResult(Intent.createChooser(intent,
* "Complete action using"), PICK_FROM_FILE);
*/
}
}
});
final AlertDialog dialog = builder.create();
btnTakephoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
if (Build.VERSION.SDK_INT < 19) {
mImageCaptureUri = data.getData();
} else {
mImageCaptureUri = data.getData();
ParcelFileDescriptor parcelFileDescriptor;
try {
parcelFileDescriptor = getContentResolver()
.openFileDescriptor(mImageCaptureUri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor
.getFileDescriptor();
myBitmap = BitmapFactory
.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null) {
myBitmap = extras.getParcelable("data");
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) {
f.delete();
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
Intent n = new Intent();
n.setClass(getApplicationContext(), EffectsActivity.class);
n.putExtra("picture", byteArray);
startActivity(n);
break;
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities(
intent, 0);
int size = list.size();
if (size == 0) {
Toast.makeText(this, "Can not find image crop app",
Toast.LENGTH_SHORT).show();
return;
} else {
if (mImageCaptureUri != null) {
intent.setData(mImageCaptureUri);
}
intent.putExtra("outputX", 350);
intent.putExtra("outputY", 350);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent(new ComponentName(res.activityInfo.packageName,
res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(
res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(
res.activityInfo.applicationInfo);
co.appIntent = new Intent(intent);
co.appIntent
.setComponent(new ComponentName(
res.activityInfo.packageName,
res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(
getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Crop App");
builder.setAdapter(adapter,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
startActivityForResult(
cropOptions.get(item).appIntent,
CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
if (mImageCaptureUri != null) {
getContentResolver().delete(mImageCaptureUri, null,
null);
mImageCaptureUri = null;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
CropAction:
public class CropOption {
public CharSequence title;
public Drawable icon;
public Intent appIntent;
}
CropOptionAdapter.java
public class CropOptionAdapter extends ArrayAdapter<CropOption> {
private ArrayList<CropOption> mOptions;
private LayoutInflater mInflater;
public CropOptionAdapter(Context context, ArrayList<CropOption> options) {
super(context, R.layout.crop_selector, options);
mOptions = options;
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup group) {
if (convertView == null)
convertView = mInflater.inflate(R.layout.crop_selector, null);
CropOption item = mOptions.get(position);
if (item != null) {
((ImageView) convertView.findViewById(R.id.iv_icon))
.setImageDrawable(item.icon);
((TextView) convertView.findViewById(R.id.tv_name))
.setText(item.title);
return convertView;
}
return null;
}
}
To resolve the problem what i have done is to,
just change the code from this
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(
Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE
);
to
intent = new Intent(Intent.ACTION_PICK);
intent.setType("*/*");
intent.putExtra(
android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri
);
startActivityForResult(
Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE
);
Working like charm.
Hi i can able to crop image either rectangle shape or vowel shape,here in both case 4 coordiante points based those points we are cropping image those are left middle point,right side middle point,top and bottom middle point but,my requirement is i need to crop image based on 8 coordinates,what above i mentioned those 4 coordinates and remain 4 is top of image starting edge 1 coordinate and top of image ending corner 1 coordinate,bottom of image starting one coordinate,ending of image another coordidnate,then image we can crop different shapes,so i don't know how to crop images using 8 coordinates...using below code i can able crop image using 4 coordinates....any one help me please
MainActivity .class:
public class MainActivity extends Activity {
private Uri mImageCaptureUri;
private ImageView mImageView;
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String [] items = new String [] {"Take from camera", "Select from gallery"};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) { //pick from camera
if (item == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else { //pick from file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
}
} );
final AlertDialog dialog = builder.create();
Button button = (Button) findViewById(R.id.btn_crop);
mImageView = (ImageView) findViewById(R.id.iv_photo);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
mImageView.setImageBitmap(photo);
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) f.delete();
break;
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size == 0) {
Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent= new Intent(intent);
co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Crop App");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
#Override
public void onCancel( DialogInterface dialog ) {
if (mImageCaptureUri != null ) {
getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
}