0

I am building an android app that accesses the camera but i am wanting to save the image into a specific folder but i have no idea how to go about it. do i use a URI builder?

this is the code i have to get the image from the camera.

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); File photo = new File(Environment .DIRECTORY_PICTURES), "pic.jpg"); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo)); imageUri = Uri.fromFile(photo); startActivityForResult(intent, TAKE_PICTURE); 

1 Answer 1

3

You can create a file from your own directory like this:

private File openFileFromMyDirectory() { File imageDirectory = null; String storageState = Environment.getExternalStorageState(); if (storageState.equals(Environment.MEDIA_MOUNTED)) { imageDirectory = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "com.myapp.camera"); if (!imageDirectory.exists() && !imageDirectory.mkdirs()) { imageDirectory = null; } else { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()); return new File(imageDirectory.getPath() + File.separator + "IMG_" + dateFormat.format(new Date()) + ".jpg"); } } return null; } 

Then get bitmap from uri:

Bitmap mCameraBitmap= MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri); 

Finally save the bitmap into the file

private void saveImageToFile(File file) { if (mCameraBitmap != null) { FileOutputStream outStream = null; try { outStream = new FileOutputStream(file); if (!mCameraBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream)) { Toast.makeText(this, "Unable to save image to file.", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "Saved image to: " + file.getPath(), Toast.LENGTH_LONG).show(); } outStream.close(); } catch (Exception e) { Toast.makeText(this, "Unable to save image to file.", Toast.LENGTH_LONG).show(); } } } 
Sign up to request clarification or add additional context in comments.

2 Comments

can you clarify the openFileFromMyDirectory() method for me? I've never really used environment variable. from my understanding you create a File objet and check to see if the storage is accessible. Thats sort of where things get hazy. the instantiation of imageDirectory is sort of confusing. is the string at the end my package name?
also the return statement looks like it returns a specific image rather than just create create a file.. sorry for my non-understanding.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.