Can't save captured image to Internal storage android camera - android

I got problem when playing with image, camera, and internal storage.
So I just about to change the code that I takes from google which has functionality to save image to sdcard. So I changed that code a little bit to this following codes...
public class CameraUtility {
private String currentPhotoPath;
private String imageCategoryName;
private ActionBarActivity activity;
private static final int REQUEST_TAKE_PHOTO = 1;
public CameraUtility(String imageCategoryName, ActionBarActivity activity){
this.imageCategoryName = imageCategoryName;
this.activity = activity;
}
public String getCurrentPhotoPath(){
return currentPhotoPath;
}
public String getImageCategoryName(){
return imageCategoryName;
}
public File createImageFile() throws IOException{
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = imageCategoryName + "_" + timeStamp + "_";
File localStorage = activity.getApplicationContext().getFilesDir();
/*
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
localStorage // directory
);
*/
File image = new File(localStorage, imageFileName.concat(".jpg"));
if(!image.exists()){
image.createNewFile();
}
else{
image.delete();
image.createNewFile();
}
Log.d("LOCAL_STORAGE", localStorage.getAbsolutePath());
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
public void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(activity.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
Toast.makeText(activity.getApplicationContext(),
"Error occurred while creating the File",
Toast.LENGTH_SHORT).show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Log.d("CAPTURED_AT", currentPhotoPath);
Toast.makeText(activity.getApplication().getApplicationContext(),
"Start Taking the Picture",
Toast.LENGTH_SHORT).show();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
activity.startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
else{
Toast.makeText(activity.getApplication().getApplicationContext(),
"File was not successfully created",
Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(activity.getApplication().getApplicationContext(),
"Activity package manager is null",
Toast.LENGTH_SHORT).show();
}
}
public 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);
activity.sendBroadcast(mediaScanIntent);
}
}
As you can see, on createImageFile() method, there is some block code which have commented out, that section makes my code do save the image into external storage (sdcard).
So I want to change that code so that the camera activity save the captured image to internal storage by change that code to this one :
File image = new File(localStorage, imageFileName.concat(".jpg"));
if(!image.exists()){
image.createNewFile();
}
else{
image.delete();
image.createNewFile();
}
But when I try to confirm the image capture, the camera activity does not closed, just like in this picture...
That "check" icon button does not take any action when being pressed.
So what was happened in here?

Actually getExternalStoragePublicDirectoryis not getting the sdcard, but the primary memory that is shared among apps. So you can change it back to getExternalStoragePublicDirectory.
And also don't forget to change localStorage variable in commented code

Related

Image saved to gallery is rotated and with wrong date (1970)

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

Photo via intent does not work

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

Taking a photo and saving in custom folder, file doesn't work

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

Reading Cached Image File in Android and getting Null from BitmapFactory.decode

I am trying to get an image taken from the camera, and storing it locally in a cache to preview in an ImageView and upload to a server when needed. The bitmap that I get back is null.
Below is my code:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE){
if (resultCode == RESULT_OK){
// TODO - save the full sized image as well
if(mCurrentPhotoPath!=null){
Log.i(TAG, "Image File found!");
Bitmap imageBitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);
if (imageBitmap !=null){
Log.i(TAG, "Successfully retrieved image back.");
}
ImageView postImageView= (ImageView) getActivity().findViewById(R.id.post_image);
postImageView.setImageBitmap(imageBitmap);
}
}
}
}
String mCurrentPhotoPath;
private File createImageCache(Context context) throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = context.getCacheDir();
Log.i(TAG, "StorageDir: "+storageDir);
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;
}
Searching around one of the solutions that I found and tried was setting the BitmapFactory.Options, but it didn't work for my case.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Edit: Ran getActivity().getCacheDir().list() and found that the files are indeed saved. Also, here is the button that saves the images:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getActivity().getPackageManager())!=null){
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageCache(getActivity());
} catch (IOException ex) {
// Error occurred while creating the File
Log.i(TAG, "Error Creating File!!! No Space??");
}
// Continue only if the File was successfully created
if (photoFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}else{
Toast.makeText(getActivity(),"Please check your camera", Toast.LENGTH_SHORT).show();
Log.i(TAG, "No camera to run");
}
}
});
and found that the files are indeed saved. Just a list() will not prove that. You created the files yourself so they were there already with length 0. What is the length in bytes afterwards? I think still 0. getCacheDir() delivers internal private memory unreachable for the external picture taker. Try with getExternalCacheDir() instead.

Camera intent onActivityResult code saves (blank) image even if photo was not accepted by user

When the user clicks the cross to not accept the photo, it ends the intent in the same way it does when they accept the photo they took. It saves a file to the device gallery. But it's blank. Shouldn't clicking the cross mean that resultCode != RESULT_OK? Is there one more check I am missing? Thanks. Here's the code. Wait, I'm saving the image before activity result...this is a flawed system, but it was on the official Android Developers website. If someone can suggest a fix I would be very greatful, because I used to save the image in onActivtyResult and it did not work on some phones, causing an exception, so I changed to this.
To start the intent:
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);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
ih.galleryAddPic(mCurrentPhotoPath, this.getApplicationContext());
return image;
}
The camera intent case within onActivityResult:
else if ((requestCode == REQUEST_TAKE_PHOTO) && (resultcode == RESULT_OK)){
mProfilePicPath = mCurrentPhotoPath;
mPortraitPhoto = ih.decodeSampledBitmapFromImagePath(mCurrentPhotoPath,
GlobalConstants.PROFILE_PICTURE_RESOLUTION,
GlobalConstants.PROFILE_PICTURE_RESOLUTION);
TextView tv = (TextView) findViewById(id.ProfilePicText);
tv.setText(mProfilePicPath);
}
}catch(Exception ex){
Log.d("shkdghrfb", ex.toString());
}
}
EDIT: I changed onActivityResult to this, but to no avail (the blank image is still in my gallery afterwards, and the value of deleted is true):
else if (requestCode == REQUEST_TAKE_PHOTO){
if(resultcode == RESULT_OK){
File f = new File(mCurrentPhotoPath);
mProfilePicPath = null;
if (f.exists()) {
if (f.length() != 0){
mProfilePicPath = mCurrentPhotoPath;
mPortraitPhoto = ih.decodeSampledBitmapFromImagePath(mCurrentPhotoPath,
GlobalConstants.PROFILE_PICTURE_RESOLUTION,
GlobalConstants.PROFILE_PICTURE_RESOLUTION);
TextView tv = (TextView) findViewById(id.ProfilePicText);
tv.setText(mProfilePicPath);
}
else {
boolean deleted = f.delete();
if (deleted == true){
Log.d("camera0", "deleted");
}
else{
Log.d("camera0", "not deleted");
}
}
}
}
else{
File f = new File(mCurrentPhotoPath);
boolean deleted = f.delete();
if (deleted == true){
Log.d("camera", "deleted");
}
else{
Log.d("camera", "not deleted");
}
}
}
}catch(Exception ex){
Log.d("shkdghrfb", ex.toString());
}
}catch(Exception ex){
Log.d("shkdghrfb", ex.toString());
}
Edit Ok I believe I needed to scan the appropriate area of the SD card with a MediaScannerIntent after the delete, for it to show, as it seems to work now.
Aren't you creating file with createImageFile() ?
You may save photoFile and on result!=RESULT_OK delete it
By the way, camera apps(even default) may return wrong result. Check it in logs. If they do, just don't rely on result & check created file's size. If ==0 - delete it

Categories

Resources