Dialog to Pick Image from Gallery or from Camera

Dialog to pick image from gallery or from camera

The code below can be used for taking a photo and for picking a photo. Just show a dialog with two options and upon selection, use the appropriate code.

To take picture from camera:

Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);//zero can be replaced with any action code (called requestCode)

To pick photo from gallery:

Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 1);//one can be replaced with any action code

onActivityResult code:

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
imageview.setImageURI(selectedImage);
}

break;
case 1:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
imageview.setImageURI(selectedImage);
}
break;
}
}

Finally add this permission in the manifest file:

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

Getting an image from gallery and camera (Android Studio)

Because you are using for loop for checking Camera and Gallary Strings. You need to remove for loop and try ike below code

And also you missing break in your swith case

final CharSequence[] items = {"Camera", "Gallery"}

if (items[item].equals("Camera")){
Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if(CameraIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(CameraIntent, CAMERA_CODE);
}

}else if (items[item].equals("Gallery")){
Log.i("GalleryCode",""+GALLERY_CODE);
Intent GalleryIntent = null;
GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GalleryIntent.setType("image/*");
GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(GalleryIntent,GALLERY_CODE);
}

Second Option

You can also put break; keyword for breaking your for loop when your condition match

Allow user to select camera or gallery for image

You'll have to create your own chooser dialog merging both intent resolution results.

To do this, you will need to query the PackageManager with PackageManager.queryIntentActivities() for both original intents and create the final list of possible Intents with one new Intent for each retrieved activity like this:

List<Intent> yourIntentsList = new ArrayList<Intent>();

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

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

(I wrote this directly here so this may not compile)

Then, for more info on creating a custom dialog from a list see https://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog

How to make Select Image From Gallery or Camera in Android

Same problem happened with me. I am not able to see captured images on Samsung and MI devices mostly.

By using this library I have solved my issue.

https://github.com/coomar2841/android-multipicker-library

Android How can I call Camera or Gallery Intent Together

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

}

take picture from camera and choose from gallery and display in Image view

You can handle your camera view click this way:

cameraImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);

}
});

Do this in your activity when you return after capturing image.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if(requestCode == 0)
{
if(data != null)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
photo = Bitmap.createScaledBitmap(photo, 80, 80, false);
imageView.setImageBitmap(photo);
}
else{
}
}
}


Related Topics



Leave a reply



Submit