Getting a picture from SD card and Camera - android

I'm currently having a standard image selection (from the SD card) dialog shown when firing off this intent:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
This lists all the applications/activities that can return an image (such as Gallery).
In this same standard list, I also want to include an option that will start the Camera and return an image taken with it. The problem is I can't figure out how to do this in a non-custom way (building my own dialog with a custom layout, application image + title etc).
The Camera activity can be launched like this:
Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
URI pictureUri = Uri.fromFile(new File("dummyPath"));
camera.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
Is there an intent that will allow me to select an image from the SD card or one taken with the Camera?
Update: I have found a solution, will double check and post it here afterwards.

you can have alert dialog to show options.
Source code is given below:
AlertDialog.Builder getImageFrom = new AlertDialog.Builder(MainActivity.this);
getImageFrom.setTitle("Select Image");
final CharSequence[] opsChars = {"Take Picture", "Open Gallery"};
getImageFrom.setItems(opsChars, new android.content.DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
if(which == 0){
File file = new File( _path );
outputFileUri = Uri.fromFile( file );
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(cameraIntent, 7);
}else
if(which == 1){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Open Gallery"), 6);
}
dialog.dismiss();
}
});
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 6) {
Uri selectedImageUri = data.getData();
pickerImageView.setPadding(0, 0, 0, 0);
pickerImageView.setScaleType(ScaleType.FIT_XY);
System.gc();
String filepath = getPath(selectedImageUri);
File imagefile = new File(filepath);
try {
FileInputStream fis = new FileInputStream(imagefile);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inPurgeable=true;
options.inSampleSize =4;
bi= BitmapFactory.decodeStream(fis,null,options);
fis.close();
Bitmap bitmapToRecycle = ((BitmapDrawable)pickerImageView.getDrawable()).getBitmap();
bitmapToRecycle.recycle();
pickerImageView.setImageBitmap(bi);
pickerImageView.setPadding(0, 0, 0, 0);
pickerImageView.setScaleType(ScaleType.FIT_XY);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pickImageTextView.setText("");
}
else if(requestCode == 7){
Log.i("return", "#####");
BitmapFactory.Options options=new BitmapFactory.Options();
options.inPurgeable=true;
options.inSampleSize =4;
//Bitmap photo = BitmapFactory.decodeFile( _path, options );
Bitmap photo = (Bitmap) data.getExtras().get("data");
pickerImageView.setImageBitmap(photo);
pickerImageView.setPadding(0, 0, 0, 0);
pickerImageView.setScaleType(ScaleType.FIT_XY);
}
}
}

You can add programmatically your image to gallery like this:
Intent media = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//mCurrentPhotoPath is the path to image.
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
media.setData(contentUri);
this.sendBroadcast(media);

Related

setImageBitmap not displaying

On click, my app gives choice between camera and gallery and that picture is then displayed in an ImageView. I originally tried to display the full image and then tried to use the bitmap way but nothing works. I just get a blank ImageView. Please give me some guidance as to what I'm doing wrong and ask for clarifications if necessary:
Camera/gallery photo code:
Uri outputFileUri;
private void openImageIntent() {
// Determine Uri of camera image to save.
final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "MyDir" + File.separator);
root.mkdirs();
final String fname = "img_" + System.currentTimeMillis() + ".jpg";
final File sdImageMainDirectory = new File(root, fname);
outputFileUri = Uri.fromFile(sdImageMainDirectory);
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for(ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
startActivityForResult(chooserIntent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent returnIntent) {
super.onActivityResult(resultCode, requestCode, returnIntent);
if(requestCode == 0) {
if(resultCode == RESULT_OK) {
final boolean isCamera;
if(returnIntent == null) {
isCamera = true;
}
else
{
final String action = returnIntent.getAction();
if(action == null) {
isCamera = false;
}
else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if(isCamera) {
selectedImageUri = outputFileUri;
mainImage.setImageURI(selectedImageUri); //trying full image
}
else {
selectedImageUri = returnIntent == null ? null : returnIntent.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);
mainImage.setImageBitmap(bitmap); //trying bitmap
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
your code is 2000000000000000% ok i test it myself
Your problem is your ImageView can't show image because of image size. I try this code with ImageView like this
<ImageView
android:id="#+id/mainImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="#drawable/abc_ab_bottom_solid_dark_holo" />
If you use height and width with dp like this
android:layout_width="100dp"
android:layout_height="100dp"
You need to compress the Bitmap to show it in ImageView.
Edit your code to conversion
if(isCamera) {
selectedImageUri = outputFileUri;
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);//You can use this bitmap if need full image to further use
Bitmap bitmap2 = Bitmap.createScaledBitmap(bitmap, 600 ,600, true);//this bitmap2 you can use only for display
mainImage.setImageBitmap(bitmap2); //trying full image
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
selectedImageUri = returnIntent == null ? null : returnIntent.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);
bitmap = Bitmap.createScaledBitmap(bitmap, 600 ,600, true);
mainImage.setImageBitmap(bitmap); //trying bitmap
} catch (IOException e) {
e.printStackTrace();
}
}
If you want to take image from camera you can go with this process:
public void fromCamera(){
String path= Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/";
File file = new File(path,"IMG_"+System.currentTimeMillis()+".jpg");
file.getParentFile().mkdirs();
try {
file.createNewFile();
}catch (IOException e) {
e.printStackTrace();
}
mPicCaptureUri = Uri.fromFile(file);
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mPicCaptureUri);
startActivityForResult(intent, REQUEST_CAMERA);
}
And if you want image from gallery then :
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, getString(R.string.select_file)), REQUEST_GALLERY);
On your onActivityResult you can get the image path of selected one and set image in image view....
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if (requestCode == REQUEST_GALLERY && data != null && data.getData() != null) {
Uri selectedImageUri = data.getData();
//do set your image here
}else if(requestCode == REQUEST_CAMERA){
if(mPicCaptureUri!=null){
//do try to set image here
}
}
}
}
don't forgrt to define mPicCaptureUri at the top as:
private Uri mPicCaptureUri = null;
You can take idea from above code ..it might help you
Now you could use Picasso Library :D
Picasso.with(context)
.load(item.getPhotoUri())
.resize(512,512)
.placeholder(R.drawable.noimage)
.error(R.drawable.error_image)
.into(photo);
This mostly happens due to image being too big to be rendered by bitmap within that span of nano second during runtime, so you won't see it. Use a library called Glide. It solved all my image issues in Android including performance when there are hundreds of images to be displayed in a single list or grid.

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 make intent chooser for camera or gallery application in android like whatsapp editprofile?

I am developing an application where i need to have a dialog choose for uploading image from gallery or camera. I have found kind of solution here Dialog to pick image from gallery or from camera but the problem is here there is clash in comparing which action is chosen by user.
I would like to know if i can modify in this code and get some result to differentiate either gallery or camera is chosen and then apply action.
Create new method into Main Activity File called “selectImage()”..for choose option
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.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, REQUEST_CAMERA);
} 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"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
Now we need return back to our activity with proper Result.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
File f = new File(Environment.getExternalStorageDirectory()
.toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(f.getAbsolutePath(),
btmapOptions);
// bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
ivImage.setImageBitmap(bm);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream fOut = null;
File file = new File(path, String.valueOf(System
.currentTimeMillis()) + ".jpg");
try {
fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
String tempPath = getPath(selectedImageUri, MainActivity.this);
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
ivImage.setImageBitmap(bm);
}
}
}
Add this method in onactivity()
public String getPath(Uri uri, Activity activity) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = activity
.managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Just an advice when you call startActivityForResult() to take a photo with camera:
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(cameraIntent, REQUEST_CAMERA);
}
Notice that the startActivityForResult() method is protected by a condition that calls resolveActivity(), which returns the first activity component that can handle the intent. Performing this check is important because if you call startActivityForResult() using an intent that no app can handle, your app will crash. So as long as the result is not null, it's safe to use the intent.

Out of memory in onActivityResult

I have gallery intent that copy imege to folder, and the all that images shown in the ListView. I have an OutOfMemory Exception with bitmap decoding in my compress method - what is the simpliest way to fix it? I have recycle() option, but it's not helped.
here is my onActivityResult and compress:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
//Toast.makeText(this, selectedImagePath, Toast.LENGTH_SHORT).show();
File sdcard = Environment.getExternalStorageDirectory();
String path = "MANUAL/workflow/img" + actions.id() + ".png";
String pathCom = "/MANUAL/workflow/img" + actions.id() + ".png";
File from = new File(selectedImagePath);
File to = new File(sdcard, path);
try {
copy(from, to);
compress(pathCom);
} catch (IOException io){}
//from.renameTo(to);
}
}
}
public void compress(String comp) {
try {
String path = Environment.getExternalStorageDirectory() + comp;
BitmapFactory.Options buffer = new BitmapFactory.Options();
buffer.inSampleSize = 1;
Bitmap bmp = BitmapFactory.decodeFile(path, buffer);
if (bmp.getWidth() > width || bmp.getHeight() > height){
Bitmap resized = Bitmap.createScaledBitmap(bmp,(int)(bmp.getWidth()*0.2), (int)(bmp.getHeight()*0.2), true);
bmp.recycle();
FileOutputStream out = new FileOutputStream(path);
resized.compress(Bitmap.CompressFormat.PNG, 70, out);
resized.recycle();
out.flush();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
Log.e("saveBitmap", e.getMessage());
}
}
herу is my intent:
switch (item.getItemId()) {
case R.id.gallery:
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
Your inSampleSize is set to 1 which means its basically not being used.. 1= no downsampling 2 would be 1/2, 4 a 1/4.
also look into this http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
hope that helps.
also if the purpose of this is to just simply create a scaled image file, perhaps that task should be handled on it's own thread using an AsyncTask for that image resizing

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