Here is my code for the Camera Activity that captures then store the photo.
private void cameraIntent(){
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
BuildConfig.APPLICATION_ID + ".provider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, TAKE_IMAGE_CODE);
}
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "MyApp" + timeStamp + ".jpeg";
File storageDir = Environment.getExternalStorageDirectory();
File dir = new File(storageDir.getAbsolutePath()+ "/Pictures/MyApp/");
dir.mkdir();
File image_file = new File(dir, imageFileName);
currentPhotoPath = image_file.getAbsolutePath();
return image_file;
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
Log.d("galleryAddPic", contentUri.toString());
}
And I'm calling these methods by:
case R.id.photoSelection_Camera:
cameraIntent();
galleryAddPic();
break;
The photo does get saved in the folder when I took a look in the device folder.
However it takes really long time for me to see the photo from the gallery.
Anyone know what is the issue here?
Related
In my application, the code below enables the user to open the camera and take photo and save to Gallery, the code is working and the photo is saved to the gallery, but the problem is that the photo appears in the gallery rotated and in the end of the gallery with date equal to 1970, please can someone help me to fix these two problems? Thanks in advance. Below is my code:
code of capturing photo:
private void dispatchTakePictureIntent() {
Intent 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
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"myapplication.project",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_CAPTURE_TAG);
}
}
}
code of creating image file:
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
method of saving photo to gallery:
public final void notifyMediaStoreScanner(final File file) {
try {
MediaStore.Images.Media.insertImage(getApplicationContext().getContentResolver(),
file.getAbsolutePath(), file.getName(), null);
getApplicationContext().sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OnActivityResult method:
if (requestCode == CAMERA_CAPTURE_TAG && resultCode == Activity.RESULT_OK) {
//Bundle extras = data.getExtras();
//imageBitmap = (Bitmap) extras.get("data");
//imageSelected.setImageBitmap(imageBitmap);
File f =new File(currentPhotoPath);
notifyMediaStoreScanner(f);
}
I want to save image taken from the camera in private files and internal storage of my app, and everything works fine but in android 4.4 when I want to save it in the private files the image is not saved.
Here my code:
public static void dispatchTakePictureIntent(Fragment fragment) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
boolean isKitKat = isKitKat();
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(fragment.getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile(fragment.getActivity());
} catch (IOException ex) {
// Error occurred while creating the File
ex.getMessage();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI=null;
photoURI = (isKitKat) ?
Uri.fromFile(photoFile) : FileProvider.getUriForFile(fragment.getActivity(),
"com.example.android.fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
fragment.startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
public static File createImageFile(Activity activity) throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
isInternalStorage = MyApplication.getPreferences().getSaveLocation();
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = (isInternalStorage==StorageLocation.INTERNAL_STORAGE.getLocation()) ? Environment.getExternalStorageDirectory() : activity.getFilesDir();
storageDir = new File(storageDir,File.separator+FOLDER_MAIN+File.separator+FOLDER_PICTURES+File.separator+FOLDER_PHOTOS);
Log.i(TAG,"final path: "+ storageDir.getAbsolutePath());
File image = new File(storageDir,imageFileName.concat(".jpg"));
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images_internal" path="test/pictures/photos" />
<files-path name="my_images_private" path="test/pictures/photos"/>
</paths>
I'm trying to read and display the picture taken using camera Intent.
My code is based on examples found in android docs:
public void takeSidePhoto(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile(REQUEST_IMAGE_CAPTURE_SIDE);
} catch (IOException ex) {
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this, "my.app.package.fileprovider", photoFile);
imageSide = photoURI.toString();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE_SIDE);
}
}
}
private File createImageFile(int imageCaptureCode) throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return image;
}
The problem is that the photoURI passed to takePictureIntent is (example):
file:/storage/emulated/0/Android/data/my.app.package/files/Pictures/JPEG_20160921_123241_562024049.jpg
But when I'm browsing my test device storage with file manager, I can see that the picture that was taken is stored at:
file:/storage/Android/data/my.app.package/files/Pictures/JPEG_20160921_123241_562024049.jpg
What is happening and how do I get the path to the real file?
in your try block do something like this to get the path
if(photoFile.exists()){
String path = photoFile.getAbsolutePath()
}
The takeSidePhoto() method should have following content:
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
imageUri = Uri.fromFile(photoFile);
} catch (IOException ex) {
Toast.makeText(getActivity(), ex.toString(), Toast.LENGTH_SHORT).show();
}
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
} else {
Toast.makeText(getActivity(), R.string.no_camera_error_message, Toast.LENGTH_SHORT).show();
}
And in createImageFile() method change this line File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
with this File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
Get storage directory using below code and save image to the path.
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
Pictures taken by my app, in Windows Explorer have always 0 bytes and can't be opened. I can only see them in Android Gallery app.
I am taking photo with this method :
private void takePhoto() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = PhotoUtils.createImageFile(this);
} catch (IOException ex) {
Log.v("MainActivity", "Creating image exception");
}
if (photoFile != null) {
fileUri = Uri.fromFile(photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
And this is PhotoUtils.createImageFile(...) :
public static File createImageFile(Context context) throws IOException {
String currentPhotoPath;
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "ES_" + timeStamp;
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
currentPhotoPath = image.getAbsolutePath();
galleryAddPic(context, currentPhotoPath);
return image;
}
public static void galleryAddPic(Context context, String currentPhotoPath) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);
}
You are indexing the file when it is zero bytes long, in the form of your temp file. Try moving your galleryAddPic() call until after the picture has been taken.
I´ve been struggling with this for a few days now and other answers posted in similar questions here on stackoverflow haven´t helped me.
What I want to do is set a custom ArrayAdapter to my ListView and inside this adapter I want to set an onClickListener to a button that appears in every item. Then I want the user to pick whether he wants to take a picture with the camera or choose a picture from the gallery. Then I want the picture to save in the app´s own folder inside Gallery. However, although the custom folder is created and visible in Gallery, the picture itself is stored in the Camera folder and I can see a broken file in the custom folder.
I´ve read photobasics on the devsite http://developer.android.com/training/camera/photobasics.html, but it did not help much.
I implemented the onActivityResult inside my Fragment but the Uri path is different fro the one created in the adapter.
Here is the code:
In ArrayAdapter:
photoPicker.setOnClickListener(new View.OnClickListener()
{
#Override public void onClick(View v)
{
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = mContext.getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam)
{
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Vyber zdroj");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
if (chooserIntent.resolveActivity(mContext.getPackageManager()) != null)
{
// Create the File where the photo should go
File photoFile = null;
try
{
photoFile = createImageFile();
}
catch (IOException ex)
{
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null)
{
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
Log.i(TAG,"uri from file:"+Uri.fromFile(photoFile).toString());
chooserIntent.putExtra("path",mCurrentPhotoPath);
fragment.startActivityForResult(chooserIntent, FlowListUtils.getIdFromDate(experience.getDate()));
}
}
}
});
private File createImageFile() throws IOException
{
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
String storagePath = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getPath()+"/MyApp";
File storageDir = new File(storagePath);
storageDir.mkdirs();
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
Log.i(TAG,"mCurrent Photo Path in adapter:"+mCurrentPhotoPath);
return image;
}
This code is in my Fragment
#Override public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
ExperienceAdapter.dateForPicture = requestCode;
ExperienceAdapter.uriForPicture = data.getData();
galleryAddPic(path);
}
private void galleryAddPic(String path)
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(ExperienceAdapter.mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
}
The path I add to the intent is file:/storage/emulated/0/Pictures/MyApp/JPEG_20140626_133228_1332202116.jpg
but suddenly changes to content://media/external/images/media/6273 in the Intent return by onActivityResult.
Where am I going wrong?
Here is the function to save the Image,
public static String saveImageInExternalCacheDir(Context context, Bitmap bitmap, String myfileName) {
String fileName = myfileName.replace(' ', '_') + getCurrentDate().toString().replace(' ', '_').replace(":", "_");
String filePath = (context.getExternalCacheDir()).toString() + "/" + fileName + ".jpg";
try {
FileOutputStream fos = new FileOutputStream(new File(filePath));
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
return filePath;
}
You have a really good example here -> Taking Photos Simply.
When you go save with createImageFile function you can choose your directory url:
private File createImageFile() throws IOException {
// Create an image file name
timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);]
File image = File.createTempFile(
imageFileName,
".jpg",
storageDir
);
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
I think this is what you need!