How can save camera photo in a file of mobile devi

2019-08-29 00:01发布

问题:

There is camera codes in my project that another developer who wrote. It takes photo by the device camera but it doesn't save photo in a file of device. It must to save the photo in a file of mobile device. I post here java class and other codes that is related with camera. How can save the photo in device?

SendMessagePage.java
public class SendMessagePage extends BaseActivity {
 private static final int CAMERA_RQ = 6969;
    private static final int PERMISSION_RQ = 84;
    File saveDir = null;
@Override
    protected void onCreate(Bundle savedInstanceState) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            saveDir = new File(Environment.getExternalStorageDirectory(), "MaterialCamera");
            saveDir.mkdirs();
        }
        final MaterialCamera materialCamera =
                new MaterialCamera(this)
                        .saveDir(saveDir)
                        .showPortraitWarning(true)
                        .allowRetry(true)
                        .defaultToFrontFacing(true)
                        .allowRetry(true)
                        .autoSubmit(false)
                        .labelConfirm(R.string.mcam_use_video);
        LinearLayout takePhoto = (LinearLayout) findViewById(R.id.take_photo);

        takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(SendMessagePage.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {

                    if (ActivityCompat.shouldShowRequestPermissionRationale(SendMessagePage.this,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

                    } else {

                        if (1 == 2) {

                        }
                        ActivityCompat.requestPermissions(SendMessagePage.this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 23
                        );
                    }
                }
                saveDir = new File(Environment.getExternalStorageDirectory(), "MaterialCamera");
                saveDir.mkdirs();
                materialCamera
                        .stillShot() // launches the Camera in stillshot mode
                        .labelConfirm(R.string.mcam_use_stillshot);
                materialCamera.start(CAMERA_RQ);

            }
        });
    }

    private String readableFileSize(long size) {
        if (size <= 0) return size + " B";
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.##").format(size / Math.pow(1024, digitGroups))
                + " "
                + units[digitGroups];
    }
    private String fileSize(File file) {
        return readableFileSize(file.length());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Received recording or error from MaterialCamera
        if (requestCode == CAMERA_RQ) {
            if (resultCode == RESULT_OK) {
                final File file = new File(data.getData().getPath());
                Toast.makeText(
                        this,
                        String.format("Saved to: %s, size: %s", file.getAbsolutePath(), fileSize(file)),
                        Toast.LENGTH_LONG)
                        .show();
            } else if (data != null) {
                Exception e = (Exception) data.getSerializableExtra(MaterialCamera.ERROR_EXTRA);
                if (e != null) {
                    e.printStackTrace();
                    Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(
            int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(
                    this,
                    "Videos will be saved in a cache directory instead of an external storage directory since permission was denied.",
                    Toast.LENGTH_LONG)
                    .show();
        }
    }

回答1:

Define this in your class

private static final int CAMERA_REQUEST = 1888;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
Uri picUri;
File imagefile;

Use the below code for capturing picture. The picture is saved in DCIM folder

takePicture.setOnClickListener(new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public void onClick(View v) {

                if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
                } else {
                    File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                    String pictureName = getPictureName();
                    imagefile = new File(pictureDirectory, pictureName);
                    picUri = Uri.fromFile(imagefile);
                    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
                    startActivityForResult(cameraIntent, CAMERA_REQUEST);
                }

            }
        });


protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {

        imageView.setImageURI(picUri);
    }
}
private String getPictureName() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
    String timestamp = sdf.format(new Date());
    nameOfFile=timestamp + ".jpg";
    return timestamp + ".jpg";

}

NOTE: This code is working and has no errors as i have used this code in one of my projects. It has been extracted from code of mine.