接上一篇预览后的拍照功能,在准备做拍照功能前为了不让代码看起来太乱,我把之前的starview的代码放到自己的创建的一个方法中startpreview(SurfaceHolder h)
然后在if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED)下面直接调用
开始正文,这个拍照并没有实现图片保存,只是让屏幕停留在当前帧数,要怎么保存可以自己去看看大佬们的文章,我后面也不确定会不会更新
现在layout的xml文件中添加button,回到主类中Button take_picture=findViewById(R.id.snapshot);
然后给按钮添加监听器与方法t
ake_picture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {}
在onClick方法中调用Camera.takePicture方法,在调用需要先new一个ShutterCallback和一个PictureCallback代码如下
Camera.ShutterCallbackshutterCallback=new Camera.ShutterCallback() {
@Override
public void onShutter() {
}
};
Camera.PictureCallbackpictureCallback=new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
}
};
然后就可以设置takePicture方法的参数了
camera.takePicture(shutterCallback,null,pictureCallback);
这里参数的意思我就不解释了,查看源码就知道了。下面是全部的代码
package com.example.testdemo2;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.SurfaceTexture;
import android.os.Bundle;
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
public class MainActivityextends AppCompatActivityimplements Shutter {
private Cameracamera;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SurfaceView v=findViewById(R.id.surfaceView);
Button take_picture=findViewById(R.id.snapshot);
SurfaceHolder h=v.getHolder();
take_picture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
camera.takePicture(shutterCallback,null,pictureCallback);
}
});
if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED) {
startpreview(h);
}
}
public void startpreview(SurfaceHolder h){
h.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder h) {
camera=camera.open();
camera.setDisplayOrientation(90);
try {
camera.setPreviewDisplay(h);
camera.startPreview();
}catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.release();
}
});
}
Camera.ShutterCallbackshutterCallback=new Camera.ShutterCallback() {
@Override
public void onShutter() {
}
};
Camera.PictureCallbackpictureCallback=new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
}
};
}