Capture Image from Camera and Display in Activity

前端 未结 16 1035
悲&欢浪女
悲&欢浪女 2020-11-21 06:43

I want to write a module where on a click of a button the camera opens and I can click and capture an image. If I don\'t like the image I can delete it and click one more i

16条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 07:19

    I know it's a quite old thread, but all these solutions are not completed and don't work on some devices when user rotates camera because data in onActivityResult is null. So here is solution which I have tested on lots of devices and haven't faced any problem so far.

    First declare your Uri variable in your activity:

    private Uri uriFilePath;
    

    Then create your temporary folder for storing captured image and make intent for capturing image by camera:

    PackageManager packageManager = getActivity().getPackageManager();
    if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
        File mainDirectory = new File(Environment.getExternalStorageDirectory(), "MyFolder/tmp");
             if (!mainDirectory.exists())
                 mainDirectory.mkdirs();
    
              Calendar calendar = Calendar.getInstance();
    
              uriFilePath = Uri.fromFile(new File(mainDirectory, "IMG_" + calendar.getTimeInMillis()));
              intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
              intent.putExtra(MediaStore.EXTRA_OUTPUT, uriFilePath);
              startActivityForResult(intent, 1);
    }
    

    And now here comes one of the most important things, you have to save your uriFilePath in onSaveInstanceState, because if you didn't do that and user rotated his device while using camera, your uri would be null.

    @Override
    protected void onSaveInstanceState(Bundle outState) {
         if (uriFilePath != null)
             outState.putString("uri_file_path", uriFilePath.toString());
         super.onSaveInstanceState(outState);
    }
    

    After that you should always recover your uri in your onCreate method:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
             if (uriFilePath == null && savedInstanceState.getString("uri_file_path") != null) {
                 uriFilePath = Uri.parse(savedInstanceState.getString("uri_file_path"));
             }
        } 
    }
    

    And here comes last part to get your Uri in onActivityResult:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {    
        if (resultCode == RESULT_OK) {
             if (requestCode == 1) {
                String filePath = uriFilePath.getPath(); // Here is path of your captured image, so you can create bitmap from it, etc.
             }
        }
     }
    

    P.S. Don't forget to add permissions for Camera and Ext. storage writing to your Manifest.

提交回复
热议问题