Custom photo folder showing up in Gallery - android

I'm working on an app that uses the camera and saves the pictures to DCIM/MyAppFolder. My first question is should I be saving it to DCIM or Pictures? If it even matters. My second question is I noticed it takes a while for the folder/pictures to show up in the native gallery app. After testing this with other apps (Instagram, Snapseed, ect) those photos show up immediately. Is there a piece of code I'm missing to accomplish this? My code is as followed:
public void takePhoto() {
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
//folder stuff
File imagesFolder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "MyAppFolder");
imagesFolder.mkdirs();
//String filePath = "/MyImages/QR_" + timeStamp + ".png" ;
File image = new File(imagesFolder, "IMG_" + timeStamp + ".jpg");
imageUri = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(imageIntent, TAKE_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
}
}
}

to update the gallery app. simply after you click save just put this simple code after saving.
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
this code will tell the gallery app that something has been added so please rescan for media now :D.

Related

How to attach images from different paths to an email?

I am using an intent to send email with subject, content and attached images
everything works fine except some of the images don't get attached
File path for successfully attached photos is like:
content://media/external/images/media/14960
File path for Unsuccessfully attached photos is like:
content://com.android.providers.media.documents/document/image%3A14745
I am using this code
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("message/rfc822");
//emailIntent.setType("application/image");
emailIntent.putExtra(Intent.EXTRA_EMAIL , new String[]{""});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, mNotes.get(position).getTitle());
emailIntent.putExtra(Intent.EXTRA_TEXT , mNotes.get(position).getContent());
ArrayList<String[]> photos = StringManipulation.imgDeserialize(mNotes.get(position).getImgUrls());
for (String[] photo : photos){
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(photo[0]));
}
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
How can i made all the photos get attached to the email?
I got this Uris by taking permissions for CAMERA, READ and WRITE EXTERNAL STORAGE
//.... onCreate...
//initialize the textview for starting the camera
TextView takePhoto = (TextView) view.findViewById(R.id.tvTakeCameraPhoto);
takePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: starting camera.");
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, Permissions.CAMERA_REQUEST_CODE);
}
});
//Initialize the textview for choosing an image from memory
TextView selectPhoto = (TextView) view.findViewById(R.id.tvChoosePhotoFromMemory);
selectPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: accessing phones memory.");
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, Permissions.PICK_FILE_REQUEST_CODE);
}
});
//.................
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
/*
Results when taking a new image with camera
*/
if(requestCode == Permissions.CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_OK){
Log.d(TAG, "onActivityResult: done taking a picture.");
//get the new image bitmap
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
Log.d(TAG, "onActivityResult: received bitmap: " + bitmap);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getActivity(), bitmap);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File takenPhotoFile = new File(tempUri.toString());
mOnPhotoReceived.getImagePath(takenPhotoFile.getPath());
getDialog().dismiss();
}
/*
Results when selecting new image from phone memory
*/
if(requestCode == Permissions.PICK_FILE_REQUEST_CODE && resultCode == Activity.RESULT_OK){
Log.d(TAG, "onActivityResult: done choosing image");
Uri selectedImageUri = data.getData();
File file = new File(selectedImageUri.toString());
Log.d(TAG, "onActivityResult: images: " + file.getPath());
//send the bitmap and fragment to the interface
mOnPhotoReceived.getImagePath(file.getPath());
getDialog().dismiss();
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
then passing the listener to the activity.
First, your app on its own needs permissions to read the content identified by those Uri values. You do not indicate where and how you get those Uri values, but you only have a short time to use them, in general. If you do not have read access to the content, you will be out of luck.
Second, add this line before the startActivity() call:
emailIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
This passes your read permission along to whatever app processes this Intent.

Android take and display photo from camera full resolution

I need to take a photo from my app and display it on an imageView, so now I´m using an intent request:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
bm = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(bm);
}
}
}
The problem is that this code gets the thumbail of the image, not the image itself in full resollution, and I don´t know how to get it. I´ve searched and I have found this https://developer.android.com/training/camera/photobasics.html , but as I´m starting with this i don´t understand it.
Could somebody help me please?
Before you call CameraIntent create a file and uri based on that filepath as shown here.
filename = Environment.getExternalStorageDirectory().getPath() + "/test/testfile.jpg";
imageUri = Uri.fromFile(new File(filename));
// start default camera
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
imageUri);
startActivityForResult (cameraIntent, CAMERA_PIC_REQUEST);
Now, you have the filepath you can use it in onAcityvityResult method as following,
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode != CAMERA_PIC_REQUEST || filename == null)
return;
ImageView img = (ImageView) findViewById(R.id.image);
img.setImageURI(imageUri);
Try out this code, It works for me.
Open camera using below code:
Intent intent = new Intent();
try {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)&& !Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED_READ_ONLY)) {
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator+ ".your folder name"
+ File.separator + "picture").getPath());
if (!file.exists()) {
file.mkdirs();
}
capturedImageUri = Uri.fromFile(File.createTempFile("your folder name" + new SimpleDateFormat("ddMMyyHHmmss", Locale.US).format(new Date()), ".jpg", file));
intent.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
startActivityForResult(intent, Util.REQUEST_CAMERA);
} else {
Toast.show(getActivity(),"Please insert memory card to take pictures and make sure it is write able");
}
} catch (Exception e) {
e.printStackTrace();
}
In onActivityResult retrieve path of captured image:
try {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && !Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED_READ_ONLY)) {
File file = new File(Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator
+ ".captured_Images"+ File.separator+ "picture").getPath());
if (!file.exists()) {
file.mkdirs();
}
selectedPath1 = capturedImageUri.toString().replace("file://", "");
Logg.e("selectedPath1", "OnactivityResult==>>" + selectedPath1);
imageLoader.displayImage(capturedImageUri.toString(), imgCarDetails1);
} else {
Toast.show(getActivity(), "Please insert memory card to take pictures and make sure it is write able");
}
} catch (Exception e) {
e.printStackTrace();
}
Add this permission in Manifest file:-
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
None of the answers worked for me, and I couldn´t use the tutorial as when creating the FileProvider, the xml gives me an error.
Finally I found this answer which works like a charm. Android Camera Intent: how to get full sized photo?

Android : Use Camera to display image to ImageView and Save to Gallery

I am making an app which has an option to get an image from the camera or from the gallery and display it in an ImageView.
I got this from the Android Developers Tutorial.
I am using a DialogInterface for this one:
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(ReportIncident.this);
builder.setTitle("Add Picture");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
try {
photoFile = createImageFile();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, 0);
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
}
} 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"), 1);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
createImageFile creates the directory/File where the photo will be saved:
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "FIREFLOOD_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
The 'Choose from Library' part is already working but I have a problem with 'Take Photo' part. Specifically on this line:
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
galleryAddPic();
startActivityForResult(takePictureIntent, 0);
Having the putExtra() and galleryAddPic() before the startActivityOnResult()
crashes the app after taking the picture but successfully saves the image to
gallery. But deleting these two methods from the code displays the photo taken
to the ImageView reportImage.
startActivityForResult displays the image taken to the ImageView through activityOnResult:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1) {
onSelectFromGalleryResult(data);
}else if (requestCode == 0) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
reportImage.setImageBitmap(imageBitmap);
}
}
}
Saving the image to gallery is performed by galleryAddPic:
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
The question is where can I put these two methods (putExtra and
galleryAddPic) to make these two funtions work:
display the photo taken to ImageView
save the photo to gallery at the same time.
I can't make these two work altogether. Please help. I tried to put
the putExtra and galleryAddPic on the onAcitivityResult but it still
crashes. galleryAddPic won't work without the putExtra.
This tutorial will help you try this link
http://www.androidhive.info/2013/09/android-working-with-camera-api/

How to pass the captured image to a different activity to set to the image view in android and store in a databse

Can anybody tell how to pass the captured image to a different activity to set the image view in android and store in a database? Can anybody provide code?
Thanks
Try this...
1.Capture and get the bitmap of the captured image in the onActivityResult()
public void capture(View view) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAPTURE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == CAPTURE_REQUEST) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
}
}
}
2 Send the Image to the next Activity...You can send the Bitmap because it implements Parcelable
private void sendImage() {
Intent intent = new Intent(MainActivity.this, NextActivity.class);
intent.putExtra("image", thumbnail);
startActivity(intent);
}
3 Get the image in the NextActivity
Bundle extras = getIntent().getExtras();
if (extras != null) {
Bitmap image = (Bitmap) extras.get("image");
if (image != null) {
imageView.setImageBitmap(image);
}
}
you need to follow these steps :-
capture image using camera
save this image
get the file URI
In your next activity you can show this image using that file URI
let me know if you have any issue.
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}

Android: Saving taken picture to Imagefolder

I just want to save a picture in my Imagefolder in my phone.
I have got 2 examples which I tried.
1. Example
My app crashes when I activate the onClick Method:
public void onClick(View arg0) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 1337);
}});
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if( requestCode == 1337)
{
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
}
else
{
Toast.makeText(AndroidCamera.this, "Picture NOt taken", Toast.LENGTH_LONG);
}
super.onActivityResult(requestCode, resultCode, data);
}
2. Example
Before I saved my taken Picture with Uri. But it saved my picture in a folder, which I can only access on my PC or with a FileApp. I don´t know how I can change the Path direction with Uri to my existing default image folder in my phone.
Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());
This is how I manage with saving images to specified imagefolder
When starting camera intent I define path and directory, where my image should be saved, and pass this as intetn extra when starting camera:
private void startCameraIntent() {
//create file path
final String photoStorePath = getProductPhotoDirectory().getAbsolutePath();
//create file uri
final Uri fileUri = getPhotoFileUri(photoStorePath);
//create camera intent
final Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//put file ure to intetn - this will tell camera where to save file with image
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start activity
startActivityForResult(cameraIntent, REQUEST_CODE_PHOTO_FROM_CAMERA);
//start image scanne to add photo to gallery
addProductPhotoToGallery(fileUri);
}
And here are some of helper methods used in code above
private File getProductPhotoDirectory() {
//get directory where file should be stored
return new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES),
"myPhotoDir");
}
private Uri getPhotoFileUri(final String photoStorePath) {
//timestamp used in file name
final String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.US).format(new Date());
// file uri with timestamp
final Uri fileUri = Uri.fromFile(new java.io.File(photoStorePath
+ java.io.File.separator + "IMG_" + timestamp + ".jpg"));
return fileUri;
}
private void addProductPhotoToGallery(Uri photoUri) {
//create media scanner intetnt
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//set uri to scan
mediaScanIntent.setData(photoUri);
//start media scanner to discover new photo and display it in gallery
this.sendBroadcast(mediaScanIntent);
}

Categories

Resources