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

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}

Related

How can I save output image from camera directly to file without compression?

After compressing the file and then texting it, it recompresses again and is very choppy
I use Intent to bring up the camera. I get the result and bring up Intent to send as text.
private void takePic() {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 2);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 2) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
File file = writebitmaptofilefirst("route_image",photo);
Uri uri = Uri.fromFile(file);
fileToDelete = file;
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra("address", "8001111222");
sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
sendIntent.setType("image/jpg");
startActivityForResult(sendIntent,3);
}
else if (requestCode == 3){
if (fileToDelete.exists()) fileToDelete.delete();
}
}
public static File writebitmaptofilefirst(String filename, Bitmap source) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File mFolder = new File(extStorageDirectory + "/temp_images");
if (!mFolder.exists()) {
mFolder.mkdir();
}
OutputStream outStream = null;
File file = new File(mFolder.getAbsolutePath(), filename + ".jpg");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, filename + ".jpg");
Log.e("file exist", "" + file + ",Bitmap= " + filename);
}
try {
outStream = new FileOutputStream(file);
source.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Log.e("file", "" + file);
return file;
}
This works great except the resulting image texted is choppy. If I send the same pic that ends up in the Gallery it converts that down and the result is 100 times better at the receiving end. Can I save the Bitmap I get from the camera call directly without compression, the file will be deleted after the sending of the picture. The user actually takes the pic and then hits the send button on the default sms app.
To save an image directly without compressing use AndroidBmpUtil:
new AndroidBmpUtil().save(source, file);
Instead of
source.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
use
source.compress(Bitmap.CompressFormat.PNG, 100, outStream);
JPEG is a lossy format hence the choppy result.

Cant see taken pictures after saving as file

I want to take a picture and save it as a file on the sd-card. All works fine, the camera starts, the pictures were taking, and saving. If i check the picturefolder on my device, i see the taken picute, but if i check the folder from another actvity, i cant see the taken pictures. The same, if i check the folder from my pc. What is wrong with my code?
Here is my code for the Cameraactivity
//Init ImageView
mPhotoCapturedImageView = (ImageView) findViewById(R.id.imgViewThumbNail);
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, ACTIVITY_START_CAMERA_APP);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ACTIVITY_START_CAMERA_APP && resultCode == RESULT_OK) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
mPhotoCapturedImageView.setImageBitmap(thumbnail);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "IMAGE_" + timeStamp+ "_";
File file = new File(Environment.getExternalStorageDirectory()+ PHOTO_ALBUM + imageFileName + ".jpg");
try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
//5
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The path of PHOTO_ALBUM is
public static final String PHOTO_ALBUM = "/MyIdea/IdeaGallery/";
I found out, that SD-Card is scanning after mounting and show all new pictures. This simply line of code solve all my problems:
MediaScannerConnection.scanFile(CameraActivity.this, new String[]{file.getPath()}, new String[]{"image/jpeg"}, null);
Thanks all for the help!

Changing the path of photos clicked by camera intent

I my developing an app that clicks the photos and it should store the photos in a different folder than the default storage location. please guide me about it.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
This is the basic code, please tell me the changes needed to make in it.
You cannot change default folder location, but you can make copy of image for your use. If you want to change it, then play with system camera.
You Need to call on activity result and get captured image and store it on any location.
For my case file(image) name is currenttimestamp.jpg
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK){
try {
AssetFileDescriptor videoAsset = getContentResolver().openAssetFileDescriptor(intent.getData(), "r");
FileInputStream fis = videoAsset.createInputStream();
File tmpFile = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis()+".jpg");
FileOutputStream fos = new FileOutputStream(tmpFile);
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
}
EDIT
tell android you have copied the picture. This will make the folder show up as a gallery on the users device just pass in the path and mimetype to a media scanner connection.
conn.scanFile(fos..getAbsolutePath(),"image/*");
**End edit *
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
*Edit setup the mediascanner connection *
private static MediaScannerConnection conn;
somewhere in onCreate()
conn = new MediaScannerConnection(this, this);
conn.connect();
#Override
public void onScanCompleted(String path, Uri uri) {
// now is good time to save stuff in the database because
// the last segment of the uri is the imageId in the mediaStore.
// you can easily pull a thumbnail from the mediaStore with the imageId.
// example of getting thumbnail
//final BitmapFactory.Options bmOptions = new BitmapFactory.Options();
// bmOptions.inSampleSize = 1;
//Bitmap bm = MediaStore.Images.Thumbnails.getThumbnail(
// context.getContentResolver(), newImageId,
// MediaStore.Images.Thumbnails.MINI_KIND,
// bmOptions);
}
#Override
public void onMediaScannerConnected() {
//toast ready
// enable your camera button
}
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyProjectName");
if (!imagesFolder.exists()) {
imagesFolder.mkdirs();// <----Do Not Forget this
}
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy_HHmmss_Z");
String currentDateandTime = sdf.format(new Date());
String fileName = "image_" + String.valueOf(currentDateandTime) + ".jpg";
File 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();
}
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

Android: How do I save captured image(s) to a specific folder

I'm a total newbie in Android programming and I'm having trouble figuring how to save an image to a specific folder. Let's say i have a folder called "myCapturedImages" and I would to save it in this folder/directory. The directory is located at Internal Storage\Pictures\myCapturedImages. The pictures that I took has its size of 0 bytes and cannot be opened. I think the main problem is my onPictureTaken function. Any clue on how I should achieve the expected save directory?
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
/*Bitmap bitmapPicture
= BitmapFactory.decodeByteArray(arg0, 0, arg0.length); */
Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(VuzixCamera.this, "Image saved: " + uriTarget.toString(), 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();
}};
get the Bitmap of the image and For saving Image you can use this code
//showedImgae is your Bitmap image
public void SaveImage(Bitmap showedImgae){
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/DCIM/myCapturedImages");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "FILENAME-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
showedImgae.compress(Bitmap.CompressFormat.JPEG, 100, out);
Toast.makeText(activityname.this, "Image Saved", Toast.LENGTH_SHORT).show();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
getApplicationContext().sendBroadcast(mediaScanIntent);
}
this is simple program to launch camera and save picture to specific folder...
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs(); // <----
File image = new File(imagesFolder, "image_001.jpg");
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
Make sure that you have added WRITE_EXTERNAL STORAGE and CAMERA permissions in manifest file.

Retrieving the image from a folder : Android

public void onPictureTaken(byte[] data, Camera camera)
{
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Folder/Raw Image");
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");
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");
File filenew = new File(android.os.Environment.getExternalStorageDirectory(),"Folder/Raw Image");
bitmap=BitmapFactory.decodeFile(filenew.getAbsolutePath());
Each time when i capture image, the image save to sub folder "Raw Image" which is in a folder " Folder". I need to retrieve this image for further processing. so i used Bitmapfactory.options. All this has to be done under one button click. every image that is saved has to be processed. How can i retrieve in such a way.
If you are taking photos, what you can do is startActivityForResult, during this process you have to work with the URI. The URI is the path that you have specified for your picture.
And now during your onActivityResult(..) call you can do the following:
try {
Bitmap thumb = MediaStore.Images.Media.getBitmap(
activity.getContentResolver(), fileUri);
photo.setImageBitmap(thumb);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Where fileUri is the URI of the image I was talking about. Here photo is the ImageView. Also when working with different devices there is a possibility that you may get an error, so I best advice you to save the URI path in a SharedPreference.
You are pointing to the wrong path :
Environment.getExternalStorageDirectory().toString() + "/"+ Folder + "Raw Image"+ ".jpg";
But you have created folder like this,
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Folder/Raw Image");
Try this way, It may help you.
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Folder/RawImage");
imagesFolder.mkdirs();
File output = new File(imagesFolder,"temp" + ".jpg");
Above we have declared a static file name. The file will be replace for every image capture.
Now you know the filepath,
String mFilePath = Environment.getExternalStorageDirectory() + "Folder/RawImage/temp.jpg";
You can use this filepath in the following way to show the bitmap.
myImage.setImageUri(Uri.fromFile(new File("Your file path")));
Or with:
myImage.setImageUri(Uri.parse(new File("Your file path").toString()));
You can get the bitmap :
Bitmap bmp=BitmapFactory.decodeStream(getContentResolver().openInputStream(Your image URI));

Categories

Resources