Search code examples
androidandroid-gallery

saving an image file to a specific directory


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

Solution

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