how auto save photo from camera without asking user (easily way) - android

Hi
I'm looking for a way to save photos from the camera device directly without ask the user to save or not. I'm not implementing the Camera classes or overriding it. I'm simply using this code above. Do you have any ideas on how to do it?
TextReader tr = new TextReader(TextReader.DIRECTORY_EMPRESAS);
String path = TextReader.PARENT_PATH + "/" + TextReader.DIRECTORY_IMAGES;
String dataAtual = new SimpleDateFormat("yyMMddHHmmss").format(new Date());
if(tr.verificaDiretorios(path)){
String pictureName = dataAtual + DADOS.get(0) + ".jpg";
File pathEmpresa = new File(path + "/" + TextReader.FILE_NAME);
File imageFile;
if(pathEmpresa.exists()){
imageFile = new File(pathEmpresa, pictureName);
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
//startActivity(i);
startActivityForResult(i, 2);
}else{
if(pathEmpresa.mkdir()){
imageFile = new File(pathEmpresa, pictureName);
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
//startActivity(i);
startActivityForResult(i, 2);
}else{
throw new IllegalStateException("Não foi possivel criar o diretorio: " + pathEmpresa);
}
}

You can't do that with an Intent. You need to use the Camera class.
Refer to the documentation:
http://developer.android.com/reference/android/hardware/Camera.html
Quick Example:
Camera camera = camera.open();
camera.takePicture(null, null, new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
if (data != null) {
Bitmap picture = BitmapFactory.decodeByteArray(data);
File f = new File(Environment.getExternalStorageDirectory(), "mydir");
f.mkdirs();//Grab file directory
f = new File(f, "mypicturefilename"); //Grab picture file location
BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(f));
picture.compress(CompressFormat.JPEG, os);//Write image to file
picture.recycle(); //Clean up
}
}
});

Related

How to create separate folder for captured images with losing quality

Hi i am trying to create separate folder for captured images with out losing quality using below code but i am getting exception android.os.FileUriExposedException: file:///storage/emulated/0/myFolder/photo_20180504_102426.png exposed beyond app through ClipData.Item.getUri()
what did do mi-stack can some one correct my code
code:
String folder_main = "myFolder";
File f = new File(Environment.getExternalStorageDirectory(), folder_main);
if (!f.exists()) {
f.mkdirs();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File file = new File(Environment.getExternalStorageDirectory(), "/myFolder" + "/photo_" + timeStamp + ".png");
imageUri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, Constants.CAMERA_REQUEST_CODE);
private void onCaptureImageResult(Intent data) {
try {
Bitmap thumbnail = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
CircleImageView circleImageView = findViewById(formFields.get(imagePosition).getId());
circleImageView.setImageBitmap(thumbnail);
}
Put This on Your oncreate()
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());

Android Application quits after saving picture

Hi Guys My application quits just after the image is saved, I cannot see why, Please help?
This is the button pressed method, after the picture is taken I press save, The image gets saved where it needs to be saved but the application just quits after I press save, It does not say "Not Responding", it just quits
cam.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
leakerID = leakId.getText().toString();
String direc = "/e3softData/DCIM/";
String fileName = leakerID+".jpg";
// get the path to sdcard
File sdcard = Environment.getExternalStorageDirectory();
// to this path add a new directory path
File dir = new File(sdcard.getAbsolutePath() + direc);
// create this directory if not already created
dir.mkdir();
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File file = new File(dir, fileName);
String f = file.toString();
Uri uriSavedImage = Uri.fromFile(new File(f));
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(intent, 0);
}
});
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir = new File(Environment.getExternalStorageDirectory() + "/e3softData/DCIM/");
if (!dir.exists()) {
dir.mkdir();
}
String fileName = leakerID+".jpg";
output = new File(dir.getAbsolutePath(), fileName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(intent, 0);
}

Creating folder with user input : Android

jpegCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
//int imageNum = 0;
String Name = PatientInfo.getText().toString();
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory().toString() + Name);
imagesFolder.mkdirs();
Date d = new Date();
CharSequence s = DateFormat.format("MM-dd-yy hh-mm-ss", d.getTime());
File output = new File(imagesFolder, s.toString() + ".jpg");
// String fileName = "image_" + String.valueOf(imageNum) + ".jpg";
// File output = new File(imagesFolder, fileName);
/* while (output.exists()){
imageNum++;
fileName = "image_" + String.valueOf(imageNum) + ".jpg";
output = new File(imagesFolder, fileName);
}*/
Uri uriSavedImage = Uri.fromFile(output);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(AndroidCamera.this,
"Image saved: ",
Toast.LENGTH_LONG).show();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{}
Log.d("Log", "onPictureTaken - jpeg");
}
};
This is a code example. I am trying to create folder with a userinput when it is entered. Each time i need to create new folders on entering new username. But in this there is something missing.Any suggestions will be helpful.
Change
File imagesFolder = new File(Environment.getExternalStorageDirectory().toString() + Name);
withFile
File imagesFolder = new File(Environment.getExternalStorageDirectory(), Name);
Please be sure to have also the WRITE_EXTERNAL_PERMISSION in the manifest, and that Name is not null

Android Camera - Save image into a new folder in SD Card

I have a very simple APP which at the moment takes a picture and then saves the image. The problem at the moment is that for some reason i cannot find where the image is being saved to on the phone.
The finished outcome with what i am trying to do is when a picture is took the image then gets saved into a new folder that has been created on the SD Card, but if the folder does not already exist it will have to be made (automaticlly) before the image can be saved.
I have tried to use the answer in this question but cannot seem to incoporate it without getting the error imageIntent cannot be resolved
EDIT: Image now saving into SD Card and creating folder but overwriting the pervious image I need it to save multiple images if any one has any suggestions code has been updated
This is a snippet of my code:
PictureCallback myPictureCallback_JPG = new PictureCallback(){
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
/*Bitmap bitmapPicture
= BitmapFactory.decodeByteArray(arg0, 0, arg0.length); */
int imageNum = 0;
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Punch");
imagesFolder.mkdirs(); // <----
String fileName = "image_" + String.valueOf(imageNum) + ".jpg";
File output = new File(imagesFolder, fileName);
while (output.exists()){
imageNum++;
fileName = "image_" + String.valueOf(imageNum) + ".jpg";
output = new File(imagesFolder, fileName);
}
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(AndroidCamera.this,
"Image saved: ",
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
}};
EDIT
Code has been updated to now save multiple images in a new folder created on SD Card.
I'm purely GUESSING you forgot the necessary code from the question part of what you linked to.
The question has the following line at the very top:
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
If you just copied the code from the answer, then you would have that error because the code in the answer does not contain the instantiation of imageIntent.
Let me know if you need anything further or if I'm just totally wrong.
UPDATE (regarding image being overwritten):
You are currently using "image_001.jpg" as the string that represents the image name.
Set a variable within your Class int imageNum = 0;
Then you need to use a while loop and increment the image number - or you can create a different name for the image based on the time - that is another way to do it.
String fileName = "image_" + String.valueOf(imageNum) + ".jpg";
File output = new File(imagesFolder, fileName);
while (output.exists()){
imageNum++;
fileName = "image_" + String.valueOf(imageNum) + ".jpg";
output = new File(imagesFolder, fileName);
}
//now save the file to the sdcard using output as the file
The above code - while not tested personally - should work.
try {
super.onCreate(savedInstanceState);
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "Your Floder Name"+ File.separator);
root.mkdirs();
sdImageMainDirectory = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
startCameraActivity();
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
finish();
}
}
protected void startCameraActivity() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, 101);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==101 && resultCode==-1)
{
try
{
Uri outputFileUri= data.getData();
selectedImagePath=getPath(outputFileUri);
}
catch(Exception ex)
{
Log.v("OnCameraCallBack",ex.getMessage());
}
}
You can save multiple image. you did one mistake every time when you are capturing the photo the folder is recreating again and again.
so you have to check whether the folder is already exist or not. you have to add only one line of code
if (!imagesFolder.exists()) {
imagesFolder.mkdirs();
}
else { //do nothing}

Camera intent android

When I begin the camera intent I give it a file name I would like it to use. When I get this on the phone it uses the phones default file name. Which is no help as I need the image name later in the app.
Camera intent code...
public void onClick(View view) {
String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
System.out.println(currentDateTimeString);
filename = ("/sdcard/" + currentDateTimeString + ".jpg");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory(), filename);
outputFileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, TAKE_PICTURE);
filetype = "image/jpeg";
}
James,
Here is the function I use to capture an image and save it to a location of my choosing (sub folder with my app name).
public void imageFromCamera() {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
Log.d(TAG, "No SDCARD");
} else {
mImageFile = new File(Environment.getExternalStorageDirectory()+File.separator+"MyApp",
"PIC"+System.currentTimeMillis()+".jpg");
mTempImagePath = mImageFile.getAbsolutePath();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mImageFile));
startActivityForResult(intent, TAKE_PICTURE);
}
}

Categories

Resources