Android 启动相机拍照和保存照片

public class MainActivity3 extends AppCompatActivity {

    Uri imageUri;
    File outputImage;
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        imageView = findViewById(R.id.image);
        Button takeBtn = findViewById(R.id.button2);
        
        takeBtn.setOnClickListener((v)->{
            outputImage = new File(getExternalCacheDir(),"output_image.jpg");
            if (outputImage.exists()) outputImage.delete();
            try {
                outputImage.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            imageUri = FileProvider.getUriForFile(this,"com.example.camera.fileprovider",outputImage);

            Intent intent= new Intent("android.media.action.IMAGE_CAPTURE");
            intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
            startActivityForResult(intent,1);
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 1:
                if (resultCode == Activity.RESULT_OK){
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        imageView.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }
}

 这个是用了FileProvider去实现的,而FileProvider是继承ContentProvider的,所以要在清单文件注册:


        
    

注册时的authorities需要和使用FileProvider的保持一致,meta-data的resource去新建一个就行了:


    

完成好后点击按钮就能启用相机,拍照后返回就能在imageView上面显示出来

你可能感兴趣的:(android,java)