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

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.

Related

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

How to save image in android gallery

I try to save the image into WathsappIMG but when I go to image gallery android I don't see the image and the image there into the directory can be seen from ES File Explorer
OutputStream output;
// Find the SD Card path
File filepath = Environment.getExternalStorageDirectory();
// Create a new folder in SD Card
File dir = new File(filepath.getAbsolutePath()
+ "/WhatSappIMG/");
dir.mkdirs();
// Retrieve the image from the res folder
BitmapDrawable drawable = (BitmapDrawable) principal.getDrawable();
Bitmap bitmap1 = drawable.getBitmap();
// Create a name for the saved image
File file = new File(dir, "Wallpaper.jpg" );
try {
output = new FileOutputStream(file);
// Compress into png format image from 0% - 100%
bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, output);
output.flush();
output.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
the gallery don't displaying (necessarily) files from external storage.
this is a common mistake.
the gallery displays images stored on the media store provider
you can use this method to store image file on media store provider:
public static void addImageToGallery(final String filePath, final Context context) {
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
}
here is what you should enter, when you're about to save the picture in the Gallery
MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle , yourDescription);
That code will add the image at the end of the Gallery. so please, check your Gallery picture, to be sure
Try adding this:
MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle , yourDescription);
Fill in your details for yourBitmap, yourTitle, and yourDescription, or just leave it as "".
You need to add a MediaScannerConnection class to your function of saving the image to the gallery. This class scans for new files and folders in gallery connected with your app. Add the following class to scan the newly saved image files or new added image directory to the gallery or download Source Code
MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
Read more
For Xamarin fellows:
public static void SaveToTheGalley(this string filePath, Context context)
{
var values = new ContentValues();
values.Put(MediaStore.Images.Media.InterfaceConsts.DateTaken, Java.Lang.JavaSystem.CurrentTimeMillis());
values.Put(MediaStore.Images.Media.InterfaceConsts.MimeType, "image/jpeg");
values.Put(MediaStore.MediaColumns.Data, filePath);
context.ContentResolver.Insert(MediaStore.Images.Media.ExternalContentUri, values);
}
And don't forget about android.permission.WRITE_EXTERNAL_STORAGE permission.
As
MediaStore.MediaColumns.Data
and
MediaStore.Images.Media.insertImage
is deprecated now,
here is how I did it using bitmap
fun addImageToGallery(
fileName: String,
context: Context,
bitmap: Bitmap
) {
val values = ContentValues()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis())
}
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, fileName)
values.put(MediaStore.Images.ImageColumns.TITLE, fileName)
val uri: Uri? = context.contentResolver.insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values
)
uri?.let {
context.contentResolver.openOutputStream(uri)?.let { stream ->
val oStream =
BufferedOutputStream(stream)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, oStream)
oStream.close()
}
}
}
You should change this piece of code-
try {
output = new FileOutputStream(file);
// Compress into png format image from 0% - 100%
bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, output);
output.flush();
output.close();
String url = Images.Media.insertImage(getContentResolver(), bitmap1,
"Wallpaper.jpg", null);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Kindly refer this code worked for me:
public static boolean saveImageToGallery(Context context, Bitmap bmp) {
// First save the picture
String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "dearxy";
File appDir = new File(storePath);
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
//Compress and save pictures by io stream
boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
fos.flush();
fos.close();
//Insert files into the system Gallery
//MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
//Update the database by sending broadcast notifications after saving pictures
Uri uri = Uri.fromFile(file);
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
if (isSuccess) {
return true;
} else {
return false;
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
Use the following code to make your image visible in the gallery.
public void saveImageToGallery(Context context, Uri path) {
// Create image from the Uri for storing it in the preferred location
Bitmap bmp = null;
ContentResolver contentResolver = getContentResolver();
try {
if(Build.VERSION.SDK_INT < 28) {
bmp = MediaStore.Images.Media.getBitmap(contentResolver, path);
} else {
ImageDecoder.Source source = ImageDecoder.createSource(contentResolver, path);
bmp = ImageDecoder.decodeBitmap(source);
}
} catch (Exception e) {
e.printStackTrace();
}
// Store image to internal storage/ImagePicker directory
String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "ImagePicker";
File appDir = new File(storePath);
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
fos.flush();
fos.close();
// Broadcast the image & make it visible in the gallery
Uri uri = Uri.fromFile(file);
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
if (isSuccess) {
Toast.makeText(context, "File saved to gallery", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Failed to save", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}

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

android save images to internal storage

I'm having problems implementing this code Saving and Reading Bitmaps/Images from Internal memory in Android
to save and retrieve the image that I want, here is my code:
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory, + name + "profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
myBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
and to retrieve(I don't know if I'm doing wrong)
#Override
protected void onResume()
{
super.onResume();
try {
File f = new File("imageDir/" + rowID, "profile.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
image = (ImageView) findViewById(R.id.imageView2);
image.setImageBitmap(b);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and nothing happens so what should I change??
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
I think Faibo's answer should be accepted, as the code example is correct, well written and should solve your specific problem, without a hitch.
In case his solution doesn't meet your needs, I want to suggest an alternative approach.
It's very simple to store image data as a blob in a SQLite DB and retrieve as a byte array. Encoding and decoding takes just a few lines of code (for each), works like a charm and is surprisingly efficient.
I'll provide a code example upon request.
Good luck!
Note that you are saving the pick as name + profile.jpg under imageDir directory and you're trying to retrieve as profile.jpg under imageDir/[rowID] directory check that.
I got it working!
First make sure that your app has the storage permission enabled:
Go to Device Settings>Device>Applications>Application Manager>"your app">Permissions>Enable Storage permission!
Permissions in manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
So, if you want to create your own directory in your File Storage you can use somethibng like:
FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/camtest");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
refreshGallery(outFile);
Else, if you want to create a sub directory in your default device DCIM folder and then want to view your image in a separate folder in gallery:
FileOutputStream fos= null;
File file = getDisc();
if(!file.exists() && !file.mkdirs()) {
//Toast.makeText(this, "Can't create directory to store image", Toast.LENGTH_LONG).show();
//return;
print("file not created");
return;
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyymmsshhmmss");
String date = simpleDateFormat.format(new Date());
String name = "FileName"+date+".jpg";
String file_name = file.getAbsolutePath()+"/"+name;
File new_file = new File(file_name);
print("new_file created");
try {
fos= new FileOutputStream(new_file);
Bitmap bitmap = viewToBitmap(iv, iv.getWidth(), iv.getHeight() );
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Toast.makeText(this, "Save success", Toast.LENGTH_LONG).show();
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
print("FNF");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
refreshGallery(new_file);
Helper functions:
public void refreshGallery(File file){
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);
}
private File getDisc(){
String t= getCurrentDateAndTime();
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
return new File(file, "ImageDemo");
}
private String getCurrentDateAndTime() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String formattedDate = df.format(c.getTime());
return formattedDate;
public static Bitmap viewToBitmap(View view, int width, int height) {
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
Hope this helps!

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}

Categories

Resources