Pick Image from Gallery/Camera/DropBox etc - android

How to give user the option to choose image from Camera/Gallery/DropBox OR any other File systems from the device and show it in an activity as an ImageView object.

For picking image from Camera/Gallery/DropBox OR any other File systems from the device just call implicit intent...
Following code may helps you...
pickbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
if (Environment.getExternalStorageState().equals("mounted")){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Select Picture:"), Constants.PICK_IMAGE_FROM_LIBRARY);
}
}
});
Now use OnActivity result for getting data...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == Constants.PICK_IMAGE_FROM_LIBRARY)
{
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
mImagePath = selectedImagePath;
Bitmap photo = getPreview(selectedImagePath);
mImageViewProfileImage.setImageBitmap(photo);
}
}
public String getPath(Uri uri)
{
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public Bitmap getPreview(String fileName)
{
File image = new File(fileName);
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image.getPath(), bounds);
if ((bounds.outWidth == -1) || (bounds.outHeight == -1))
{
return null;
}
int originalSize = (bounds.outHeight > bounds.outWidth) ? bounds.outHeight : bounds.outWidth;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = originalSize / 64;
return BitmapFactory.decodeFile(image.getPath(), opts);
}
}

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

Related

Android - Take/Select picture and put it in the right imageview

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) {...}

how to get filename and path of saved image after cropping

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.

Android: Take image from any source

I'm trying to take an Image from any source (like dropbox, gallery, camera, retrica etc..),getting his path and setting it on a ImageView. by using this intent
private void cameraIntent() {
Intent pickIntent = new Intent();
pickIntent.setType("image/*");
pickIntent.setAction(Intent.ACTION_GET_CONTENT);
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String pickTitle = "Select or take a new Picture";
Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
chooserIntent.putExtra
(
Intent.EXTRA_INITIAL_INTENTS,
new Intent[]{takePhotoIntent}
);
startActivityForResult(chooserIntent, REQUEST_CAMERA);
}
But now, I can only handle Gallery and Camera intents, how can I handle other apps?
For picking image from Camera/Gallery/DropBox OR any other File systems from the device just call implicit intent...
Following code may helps you..
pickbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
if (Environment.getExternalStorageState().equals("mounted")){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Select Picture:"), Constants.PICK_IMAGE_FROM_LIBRARY);
}
}
});
Now use OnActivity result for getting data...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == Constants.PICK_IMAGE_FROM_LIBRARY)
{
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
mImagePath = selectedImagePath;
Bitmap photo = getPreview(selectedImagePath);
mImageViewProfileImage.setImageBitmap(photo);
}
}
public String getPath(Uri uri)
{
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public Bitmap getPreview(String fileName)
{
File image = new File(fileName);
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image.getPath(), bounds);
if ((bounds.outWidth == -1) || (bounds.outHeight == -1))
{
return null;
}
int originalSize = (bounds.outHeight > bounds.outWidth) ? bounds.outHeight : bounds.outWidth;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = originalSize / 64;
return BitmapFactory.decodeFile(image.getPath(), opts);
}
}
This is a full example: https://gist.github.com/felixgborrego/7943560

Saving Image path of pictures taken to Database

I'm new to android development. I am trying to create an app where when a user take a picture, it's path will be saved to the database. I am able to save and retrieve the image when it's from the gallery, But how do I save it if it's taken by camera?
Here's My Code
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Student_Profile.this);
builder.setTitle("Add Photo");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
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, 1);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
0);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult( int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK){
if (requestCode == 0) {
studentsDbAdapter.delete_Pic_byID(studID);
Uri targetUri = data.getData();
picture_location=getPath(targetUri);
// picture_location = targetUri.toString();
studentsDbAdapter.insertImagePath(studID ,picture_location);
showpic();
} }
else if (requestCode == 1) {
// How do I get The URI?
// I'm thinking that maybe if I can get the Uri
//from the new image I can save it like how I saved the image to my DB gallery style.
String pic_location=getPath(Uri);
studentsDbAdapter.insertImagePath(studID ,pic_location);
showpic();
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void showpic() {
//LoginDataBaseAdapter db = studentsDbAdapter.open();
boolean emptytab = false;
boolean empty = studentsDbAdapter.checkPic(null, emptytab);
//Cursor cursor = loginDataBaseAdapter.fetchProfileImageFromDatabase();
if(empty==false)
{
String pathName = studentsDbAdapter.getImapath(studID);
File image = new File(pathName);
if(image.exists()){
ImageView imageView= (ImageView) findViewById(R.id.studpic);
imageView.setImageBitmap(BitmapFactory.decodeFile(image.getAbsolutePath()));
}
}
}
Try this. It may help you.
if (fromGallery) {
data.getData()); //get image data like this
} else {
bm = (Bitmap) data.getParcelableExtra("data");
}

Android How can I call Camera or Gallery Intent Together

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;
}

Categories

Resources