Android 摄像头基础(调用摄像头拍照)

一、调用原相机

以下是两种调用原相机拍照并返回结果到ImageView的方法:
1)返回缩略图
2)返回原图

public class MainActivity extends Activity {
   

    private static int REQ_1 = 1;	//自定义参数
    private static int REQ_2 = 2;	//自定义参数
    private ImageView Image;
    private String mFilePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
   
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Image = findViewById(R.id.iv);

    }
    
    /**
	*调用原相机,返回缩略图
	**/
    public void startCamera1(View view){
   
        Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(it, REQ_1);
    }
    
	/**
	*调用原相机,返回原图
	*原理:将拍好的照片保存到指定路径,再将该照片从指定路径调出来
	**/
    public void startCamera2(View view){
   
        Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri photoUri=getImageUri();
        it.putExtra(MediaStore.EXTRA_OUTPUT,photoUri);
        startActivityForResult(it, REQ_2);
    }

	/**
	*将拍好的照片保存到指定路径
	**/
    public Uri getImageUri() {
   
        Uri uri;
        mFilePath = Environment.getExternalStorageDirectory().getPath()+"/FCa/"
                + System.currentTimeMillis() + ".jpg";
        File file = new File(mFilePath);
        if (!file.getParentFile().exists()) {
   
            file.getParentFile().mkdirs();
        }
        String path = file.getPath();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
   
            uri = Uri.fromFile(file);
        } else {
   
            //兼容android7.0 使用共享文件的形式
            ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, path);
            uri = this.getApplication().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        }
        return uri;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
   
            if(requestCode == REQ_1){
   //缩略图
                Bundle bundle = data.getExtras();
                Bitmap bitmap = (Bitmap) bundle.get("data");
                Image.setImageBitmap(bitmap);
            }else if(requestCode == REQ_2){
   //原图
                FileInputStream fis = null;
                try {
   
                    fis = new FileInputStream(mFilePath);
                    Bitmap bitmap = BitmapFactory.decodeStream(fis);
                    Image.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
   

你可能感兴趣的:(android)