I'm creating an application that after taking a photo, uploads it on a server (using the file path, like the tutorial on https://trinitytuts.com/capture-image-upload-server-android/).
To take the picture I followed the instructions on https://developer.android.com/training/camera/photobasics.html.
While I capture an image having an external storage, everything works fine, but if I use a device without SD (like a Nexus) app crashes.
Can you help me?
Thank you
EDIT
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Log.w("error", "ERROR");
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.application.package.fileprovider",//here I put the app pakage
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
Use this while open the camera using intent
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Log.e("Log Excepton", ex.toString() + "...");
}
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, IMAGE_CAPTURE);
}
}
Use this in on activity result
if (requestCode == IMAGE_CAPTURE) {
Log.e("Log mCurrentPhotoPath", mCurrentPhotoPath + "...");
iv_uploadimage.setImageURI(Uri.parse(mCurrentPhotoPath));
selectedImagePath1 = mCurrentPhotoPath.substring(5);
Log.e("Log Optimized path", selectedImagePath1 + "...");}
Add file write permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
This is for creating 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 = 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;
}
I think have problem in createImageFile code.
Try with this updated function
/**
* Function for create file in SD card or internal storage depending on SD card availability
* #return : file in internal / external storage
*/
private File createImageFile() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// get path of pictures folder from SD card
// give any path of your choice
return new File(Environment.DIRECTORY_PICTURES);
}else {
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// create folder of your app or get already exists folder
// ie path from internal storage
return cw.getDir("media", Context.MODE_PRIVATE);
}
}
Do not forget to add permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
After capturing image you will get the result in the ActivtyResult.
if (requestCode == CAMERA_REQUEST) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
...
}
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've written some code in a fragment to open the camera app and once a photo is taken, a photo is saved. I cannot get it to save a full size image, its saving a lower res version. Can anyone spot where I've gone wrong?
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(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
mNewPhotoPath = getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/" +
photoFile.getName();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getContext(),
"com.example.mmackenz.myholidays.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
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 = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
This is what I have in my onActivityResult in case that is relevant:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
File newImage = new File(mNewPhotoPath);
images.add(newImage);
adapter.notifyDataSetChanged();
Photo newPhoto = new Photo(newImage.getAbsolutePath(), newImage.getName(), -1, -1);
DatabaseHandler db = DatabaseHandler.getInstance(getContext());
db.addPhoto(newImage.getAbsolutePath(), newImage.getName(), -1,-1);
}
}
It adds a new file to an array list which is displayed in a recycler view, and also info of the file in a Photos table.
Thanks
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();
I use the code from the developer-website https://developer.android.com/training/camera/photobasics.html
btnPhoto.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Log.d("Button", "take photo");
dispatchTakePictureIntent();
}
});
}
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) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
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 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
Log.d("storageDir",storageDir.toString());
//File storageDir = "/Android/data/" + getApplicationContext().getPackageName() + "/files/";
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;
}
If the button is pushed the intent is started, I can take a photo, the camera is closed but no photo is taken (no photo in any folder). I don't know why, the code should work.
How did you come to the conclusion that there is no file in the Pictures folder? When you create any new file in Android, it doesn't get reflected immediately. To make that reflect in gallery, you need to scan it via MediaScannerConnection.
MediaScannerConnection.scanFile(getActivity(), new String[]{image.toString()}, null, null);
But if that's not the case: In your onActivityResult(), query the intent object that you received and see if you have the Bitmap of the image you captured.
I hope this helps : capturing images with MediaStore.ACTION_IMAGE_CAPTURE intent in android
I'm trying to take a photo with my app and save it in a folder, but for some reason the file just doesn't work. It is created just fine, but it's just an empty file (as far as I can tell).
My code:
private File createImageFile() throws IOException {
// Create an image file name
//String timeStamp = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String imageFileName = "SCB_";
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) +
File.separator + "/SCBimages/";
File storageDir = new File(path);
storageDir.mkdirs();
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;
}
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
System.out.println(ex.getMessage());
System.out.println(Arrays.toString(ex.getStackTrace()));
Toast.makeText(getApplicationContext(), "Failed" + ex.getMessage(), Toast.LENGTH_SHORT).show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra("", Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
Curiously, my phone does take a picture but it is saved in the DCMI folder under another name. Does anyone have an idea as to what the problem is?
You're missing the MediaStore.EXTRA_OUTPUT extra from your intent. I think the line:
takePictureIntent.putExtra("", Uri.fromFile(photoFile));
should probably be
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));