如何将前置摄像头添加到SurfaceView并用它拍照?

时间:2016-12-04 06:45:34

标签: java android android-layout android-studio android-fragments

您好

如何将前置摄像头视图添加到SurfaceView,就像我使用" REAL CAMERA" 一样。这是我的代码:

CameraActivity.java

   **public class CameraActivity extends Activity implements SurfaceHolder.Callback{

    Camera camera;

    @InjectView(R.id.s)
    SurfaceView surfaceView;

    @InjectView(R.id.takeaphoto)
    ImageView imageView;
    SurfaceHolder surfaceHolder;
   Camera.PictureCallback callback;
    private int cameraId = 0;
    Camera.ShutterCallback shutterCallback;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.camera_activity);



        ButterKnife.inject(this);
        surfaceHolder=surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
cameraImage();
            }
        });
        callback = new android.hardware.Camera.PictureCallback() {
            @Override
            public void onPictureTaken(byte[] bytes, android.hardware.Camera camera) {
                FileOutputStream outputStream=null;
                File file_image = getDirc();

                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyymmddhhmms");
                String date = simpleDateFormat.format(new Date());
                String photo_file="PI_"+date+".jpg";
                String file_name = file_image.getAbsolutePath()+"/"+photo_file;
                File picfile=new File(file_name);

                try {

                    outputStream=new FileOutputStream(picfile);
                    outputStream.write(bytes);
                    outputStream.close();


                }catch (FileNotFoundException e){}
                catch (IOException ex){}
                finally {

                }
                refreshCamera();
                refreshGallery(picfile);

                try {
                    camera.stopPreview();
                }catch (Exception e){}

                try{

                    camera.setPreviewDisplay(surfaceHolder);
                    camera.startPreview();
                }catch (Exception e){}


            }


        };


    }
    private void refreshGallery(File file){
        Intent intent=new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.fromFile(file));



    }

    public void refreshCamera(){

        if (surfaceHolder.getSurface() == null){

            return;

        }

    }

    private File getDirc(){

File dics = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        return new File(dics ,"Camera");

    }

    public void cameraImage(){

        camera.takePicture(null , null ,callback);
       MediaPlayer mediaPlayer = MediaPlayer.create(this , R.raw.sound);
        mediaPlayer.start();

    }


    public void surfaceCreated(SurfaceHolder surfaceHolder ) {



try {
    camera = Camera.open(0);
}catch (RuntimeException ex){}
        Camera.Parameters parameters;
        parameters = camera.getParameters();
        parameters.setPreviewFrameRate(60);
        parameters.setPreviewSize(1920 , 1080);
        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
        camera.setParameters(parameters);
        camera.setDisplayOrientation(90);



        try {

            camera.setPreviewDisplay(surfaceHolder);
            camera.startPreview();


        }catch (Exception e){



        }

    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
        refreshCamera();

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        camera.stopPreview();
        camera.release();
        camera=null;

    }

    public void frontCamera(View view) {

        if (cameraId == 0){


            try {
                camera = Camera.open(1);
            }catch (RuntimeException ex){}

            try {

                camera.setPreviewDisplay(surfaceHolder);
                camera.startPreview();


            }catch (Exception e){



            }
        }

        else{

            try {
                camera = Camera.open(0);
            }catch (RuntimeException ex){}

            try {

                camera.setPreviewDisplay(surfaceHolder);
                camera.startPreview();


            }catch (Exception e){



            }

        }




    }




}**

以及XML,如果它甚至需要它:

   <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/rel">

        <SurfaceView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/s">

        </SurfaceView>


        <RelativeLayout
            android:layout_width="match_parent"
            android:id="@+id/rel2"
            android:background="@color/colorPrimaryDark"
            android:layout_alignParentBottom="true"
            android:layout_height="150dp">

            <ImageView
                android:id="@+id/takeaphoto"
                android:background="@drawable/button_press"
                android:layout_height="80dp"
                android:layout_width="80dp"
                android:layout_centerVertical="true"
                android:layout_centerHorizontal="true" />

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:id="@+id/rel1"
            android:background="@color/colorPrimaryDark"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true">

            <ImageView
                android:layout_width="30dp"
                android:layout_marginEnd="10dp"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:src="@drawable/switchcamera"
                android:id="@+id/imageView" />

        </RelativeLayout>

    </RelativeLayout>

</FrameLayout>

更新:现在以这种方式更新我的代码,但仍显示错误,

  

连接相机时出错:1

2 个答案:

答案 0 :(得分:0)

使用此方法获取前置摄像头的ID并将其作为参数传递给camera.open(int id) 我假设您想要通过调用我更改为frontCamera(View view)的方法switchCamera(View view)来点击按钮来切换相机,并编辑您的代码,如下所示:

public class CameraActivity extends Activity implements SurfaceHolder.Callback{

Camera camera;

@InjectView(R.id.s)
SurfaceView surfaceView;

@InjectView(R.id.takeaphoto)
ImageView imageView;
SurfaceHolder surfaceHolder;
Camera.PictureCallback callback;
private int cameraId = 0;
Camera.ShutterCallback shutterCallback;
private boolean frontCamera;


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.camera_activity);



    ButterKnife.inject(this);
    surfaceHolder=surfaceView.getHolder();
    surfaceHolder.addCallback(this);
    surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            cameraImage();
        }
    });
    callback = new android.hardware.Camera.PictureCallback() {
        @Override
        public void onPictureTaken(byte[] bytes, android.hardware.Camera camera) {
            FileOutputStream outputStream=null;
            File file_image = getDirc();

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyymmddhhmms");
            String date = simpleDateFormat.format(new Date());
            String photo_file="PI_"+date+".jpg";
            String file_name = file_image.getAbsolutePath()+"/"+photo_file;
            File picfile=new File(file_name);

            try {

                outputStream=new FileOutputStream(picfile);
                outputStream.write(bytes);
                outputStream.close();


            }catch (FileNotFoundException e){}
            catch (IOException ex){}
            finally {

            }
            refreshCamera();
            refreshGallery(picfile);

            try {
                camera.stopPreview();
            }catch (Exception e){}

            try{

                camera.setPreviewDisplay(surfaceHolder);
                camera.startPreview();
            }catch (Exception e){}


        }


    };


}
private void refreshGallery(File file){
    Intent intent=new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    intent.setData(Uri.fromFile(file));



}

public void refreshCamera(){

    if (surfaceHolder.getSurface() == null){

        return;

    }

}

private File getDirc(){

    File dics = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
    return new File(dics ,"Camera");

}

public void cameraImage(){

    camera.takePicture(null , null ,callback);
    MediaPlayer mediaPlayer = MediaPlayer.create(this , R.raw.sound);
    mediaPlayer.start();

}


public void surfaceCreated(SurfaceHolder surfaceHolder ) {



    try {
        camera = Camera.open(0);
    }catch (RuntimeException ex){}
    Camera.Parameters parameters;
    parameters = camera.getParameters();
    parameters.setPreviewFrameRate(60);
    parameters.setPreviewSize(1920 , 1080);
    parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
    camera.setParameters(parameters);
    camera.setDisplayOrientation(90);



    try {

        camera.setPreviewDisplay(surfaceHolder);
        camera.startPreview();


    }catch (Exception e){



    }

}

@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
    refreshCamera();

}

@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
    camera.stopPreview();
    camera.release();
    camera=null;

}

public void switchCamera(View view) {

    if (frontCamera){


        try {
            camera = Camera.open(defaultBackCamera());
        }catch (RuntimeException ex){}

        try {

            camera.setPreviewDisplay(surfaceHolder);
            camera.startPreview();


        }catch (Exception e){



        }
    }

    else{

        try {
            camera = Camera.open(getFrontCameraId());
        }catch (RuntimeException ex){}

        try {

            camera.setPreviewDisplay(surfaceHolder);
            camera.startPreview();


        }catch (Exception e){



        }

    }




}


private int getFrontCameraId() {
    int availableCameras = Camera.getNumberOfCameras();
    Camera.CameraInfo info = new Camera.CameraInfo();
    for (int i = 0; i < availableCameras; i++) {
        Camera.getCameraInfo(i, info);
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            frontCamera = true;
            return i;
        }
    }
    return -1;
}

private int defaultBackCamera() {
    int numberOfCameras = Camera.getNumberOfCameras();
    Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
    for (int i = 0; i < numberOfCameras; i++) {
        Camera.getCameraInfo(i, cameraInfo);
        if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
            frontCamera = false;
            return i;
        }
    }
    return -1;
}




}

祝你好运1

答案 1 :(得分:0)

修改此行

camera = android.hardware.Camera.open();

camera = android.hardware.Camera.open(1);

注意:后凸轮使用id 0,前凸轮使用1。通常这对所有的fones都是一样的。所以我不认为每次都能找到id而不是开销。