Modify live camera view

2019-05-31 06:59发布

问题:

How can I modify live camera view on Android?

I was searching and found this app https://play.google.com/store/apps/details?id=com.fingersoft.cartooncamera as good example what I want to do. I wanted to apply some effect to my camera view as well. I need to find a way to add some effects or draw something on my camera view.

As far as I understood I have to get some video stream, apply some changes and show back in camera view.

Any ideas?

Much thanks!

回答1:

You can find more information about this topic Android - Camera Preview and in this post. A completely other approach would be to use OpenCV.

The smallest piece of code I could think of to get an image and preview it on the screen looks like this:

public class MainActivity extends Activity implements Callback {

    Camera camera;
    SurfaceView surfaceView;
    SurfaceHolder holder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        surfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
    }

    @Override
    protected void onResume() {
        super.onResume();
        camera = Camera.open();
        Camera.Parameters parameters = camera.getParameters();
        parameters.setPictureFormat(ImageFormat.JPEG);
        camera.setParameters(parameters);

        holder = surfaceView.getHolder();
        holder.addCallback(this);

        camera.setPreviewCallback(new PreviewCallback() {
            public void onPreviewFrame(byte[] data, Camera camera) {
                // You could apply some pixel operations directly here.
                Log.d("Camera", "Camera image aquired");
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        camera.stopPreview();
        camera.release();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            camera.setPreviewDisplay(holder);
        } catch (IOException e) {
            e.printStackTrace();
        }
        camera.startPreview();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
    }
}

A full example that does this, can be found on GitHub.