简体   繁体   English

如何将相机照片保存在移动设备文件中?

[英]How can save camera photo in a file of mobile device?

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. 我在这里发布了与相机相关的java类和其他代码。 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();
        }
    }

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 图片保存在DCIM文件夹中

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. 它是从我的代码中提取的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM