Skip to content Skip to sidebar Skip to footer

How To Configure Action_image_capture To Store The Photo In Public External Storage?

The Taking Photos Simply Documentation recommends to store image taken with device camera as 'should be saved on the device in the public external storage'. But how to do this? The

Solution 1:

see this code it will help you definitely:

private void selectImage() {

final CharSequence[] options = {"Take Photo", "Choose from Gallery"};

    AlertDialog.Builderbuilder=newAlertDialog.Builder(Maintenance.this);
    builder.setTitle("Add Photo!");
    builder.setNegativeButton("Cancle", newDialogInterface.OnClickListener() {

        @OverridepublicvoidonClick(DialogInterface dialog, int which) {

            dialog.dismiss();
        }
    });
    builder.setItems(options, newDialogInterface.OnClickListener() {
        @OverridepublicvoidonClick(DialogInterface dialog, int item) {
            if (options[item].equals("Take Photo")) {
                Intentintent=newIntent(MediaStore.ACTION_IMAGE_CAPTURE);
                Filef=newFile(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                startActivityForResult(intent, 1);
            } elseif (options[item].equals("Choose from Gallery")) {
                Intentintent=newIntent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 2);

            } /*else if (options[item].equals("Cancel")) {
                dialog.dismiss();
            }*/
        }
    });
    builder.show();
}

@OverrideprotectedvoidonActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == 1) {
            Filef=newFile(Environment.getExternalStorageDirectory().toString());

            for (File temp : f.listFiles()) {
                if (temp.getName().equals("temp.jpg")) {
                    f = temp;
                    break;
                }
            }
            try {
                Bitmap bitmap;
                BitmapFactory.OptionsbitmapOptions=newBitmapFactory.Options();

                bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
                        bitmapOptions);
                bitmap = Bitmap.createScaledBitmap(bitmap, 450, 450, false);
                ByteArrayOutputStreambytes=newByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
                // byte[] imageBytes = bytes.toByteArray();// encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);

                Camera.setImageBitmap(bitmap);

                Stringpath= android.os.Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath();
                f.delete();
                OutputStreamoutFile=null;
                file = newFile(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                //file.getPath();// String str = FileUtils.readFileToString(file, "UTF-8");
                image = file.getPath();
                String[] parts = image.split("/");
                encodedImage = parts[parts.length - 1];
                try {
                    outFile = newFileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                    outFile.flush();
                    outFile.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } elseif (requestCode == 2) {

            UriselectedImage= data.getData();
            String[] filePath = {MediaStore.Images.Media.DATA};
            Cursorc= getContentResolver().query(selectedImage, filePath, null, null, null);
            c.moveToFirst();
            intcolumnIndex= c.getColumnIndex(filePath[0]);
            picturePath = c.getString(columnIndex);
            c.close();
            Bitmapthumbnail= (BitmapFactory.decodeFile(picturePath));
            thumbnail = Bitmap.createScaledBitmap(thumbnail, 450, 450, false);
            ByteArrayOutputStreambytes=newByteArrayOutputStream();
            thumbnail.compress(Bitmap.CompressFormat.JPEG, 85, bytes);
            //  byte[] imageBytes = bytes.toByteArray();// encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
            image = picturePath;
            String[] parts = picturePath.split("/");
            encodedImage = parts[parts.length - 1];
            Camera.setImageBitmap(thumbnail);
        }
    }
} 

Solution 2:

The provided example shows rather how to save to a private folder!?

No, it does not. It shows how to save to getExternalFilesDir(). This is part of external storage, which the user can access.

You are also welcome to create yourself a subdirectory under Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), if you prefer. You will need WRITE_EXTERNAL_STORAGE on all API levels, though, including needing to set up runtime permissions on Android 6.0+.

Solution 3:

Try this

//Click Picture from camera
        camera_image.setOnClickListener(newView.OnClickListener() {
            @OverridepublicvoidonClick(View v) {

                ContentValuesvalues=newContentValues();
                values.put(MediaStore.Images.Media.TITLE, "New Picture");
                values.put(MediaStore.Images.Media.DESCRIPTION, "From your Camera");
                imageUri = getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                Intentintent=newIntent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(intent, CAMERA_CLICK_RESULT);

            }


        });

Heres the result

@OverrideprotectedvoidonActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    //Get Image from Cameraif (requestCode == CAMERA_CLICK_RESULT && resultCode == RESULT_OK) {

        Bitmapphoto=null;
        try {
            photo = MediaStore.Images.Media.getBitmap(
                    getContentResolver(), imageUri);
        } catch (IOException e) {
            e.printStackTrace();
        }
        selectedImage = getResizedBitmap(photo, 900);


        try {
            //Write fileStringfilename="/file_name";
            Stringdir_path="Directory_Path";
            Filefile=newFile(dir_path)
            file.mkdir();
            FileOutputStreamfileOutputStream=newFileOutputStream(dir_path + filename);
            selectedImage.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);

            //Cleanup
            fileOutputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

//Resize Bitmappublic Bitmap getResizedBitmap(Bitmap image, int maxSize) {
    intwidth= image.getWidth();
    intheight= image.getHeight();

    floatbitmapRatio= (float) width / (float) height;
    if (bitmapRatio > 1) {
        width = maxSize;
        height = (int) (width / bitmapRatio);
    } else {
        height = maxSize;
        width = (int) (height * bitmapRatio);
    }
    return Bitmap.createScaledBitmap(image, width, height, true);
}

Solution 4:

Action Image Capture method:

// OPEN CAMERA & TAKE PICprivatevoiddispatchTakePictureIntent() {

    try {

        IntenttakePictureIntent=newIntent(MediaStore.ACTION_IMAGE_CAPTURE);

        // Ensure that there's a camera activity to handle the intentif (takePictureIntent.resolveActivity(getPackageManager()) != null) {

            // Create the File where the photo should go//File photoFile = null;try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
                ex.printStackTrace();
                Log.e("takePic_IO_EX", ex + "");
            }

            //photoFile = createImageFile();// Continue only if the File was successfully createdif (photoFile != null) {

                UriphotoURI= FileProvider.getUriForFile(this,
                        "com.example.appname.fileprovider",
                        photoFile);


                List<ResolveInfo> resInfoList = this.getPackageManager().queryIntentActivities(takePictureIntent, PackageManager.MATCH_DEFAULT_ONLY);
                for (ResolveInfo resolveInfo : resInfoList) {
                    StringpackageName= resolveInfo.activityInfo.packageName;
                    this.grantUriPermission(packageName, photoURI, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
                /*takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                this.setResult(RESULT_OK, takePictureIntent);*/


                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        Log.e("takePic_main_EX", e + "");
    }

}

onActivity:

@Override
publicvoid onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {

        try {

            /*Log.e("mCurrentPhotoPath", mCurrentPhotoPath);
            Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);
            Log.e("displayPic", "2");
            attendanceCameraBtn.setImageBitmap(bitmap);
            Log.e("displayPic", "3");*/try {
                if (photoFile.getAbsoluteFile().getTotalSpace() <= 10) {
                    //Log.e("fileSize==2==", photoFile.getTotalSpace() + "    ++++");if (photoFile.isFile()) {
                        if (photoFile.exists()) {
                            photoFile.delete();
                            Toast.makeText(getApplicationContext(), "Photo Capture Failed, Please Retry!", Toast.LENGTH_LONG).show();
                        }
                    }

                } else {


                            //Do whatever you want here
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("file", e + "");
            }

        } catch (Exception e) {
            e.printStackTrace();
            Log.e("displayPic_EX", e + "");
            Log.e("onActivityResult_EX", e + "");
        }
    } else {

        try {
            if (photoFile.isFile()) {
                if (photoFile.exists()) {
                    photoFile.delete();
                    Toast.makeText(getApplicationContext(), "Photo Capture Cancelled!", Toast.LENGTH_LONG).show();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("onActivityResult_els_EX", e + "");
        }
    }
}

Create image Directory and Image file in private folder method:

private File createImageFile()throws IOException {

    // Create an image file nameRandomgenerate=newRandom();
    intn=10000;
    n = generate.nextInt(n);

    StringnValue= String.valueOf(n);
    StringfName="Image-" + n;


    StringfilePath= getExternalFilesDir(Environment.DIRECTORY_PICTURES).toString();
    Filedir=newFile(filePath + "/app_images");

    if (!dir.exists()) {
                dir.mkdirs();
            }

    Fileimage= File.createTempFile(
            fName,          /* prefix */".jpg",         /* suffix */
            dir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.getAbsolutePath();
    Log.e("mCurrentPhotoPath", mCurrentPhotoPath + "  ++++"); //Prints you the image file pathreturn image;
}



try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
                ex.printStackTrace();
                Log.e("takePic_IO_EX", ex + "");
            }

And create a folder named xml inside your res folder. Inside that xml folder, create an xml file and name it file_paths.xml. Mention this path inside file_paths.xml

<?xml version="1.0" encoding="utf-8"?><pathsxmlns:android="http://schemas.android.com/apk/res/android"><external-pathname="Images"path="Android/data/" /></paths>

Declare File photoFile globally. All the best!

Post a Comment for "How To Configure Action_image_capture To Store The Photo In Public External Storage?"