<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/sv_camera_surface"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="拍照"
android:onClick="takePhoto"
/>
</RelativeLayout>
public class CameraActivity extends AppCompatActivity {
private SurfaceView sv_camera_surface;
private Camera camera;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
sv_camera_surface = (SurfaceView) findViewById(R.id.sv_camera_surface);
sv_camera_surface.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
//打开摄像头
camera = Camera.open();
//设置摄像参数
Camera.Parameters parameters= camera.getParameters();
parameters.setPictureFormat(PixelFormat.JPEG);
parameters.set("jpeg-quality",100);
camera.setParameters(parameters);
//开启预览效果
camera.startPreview();
//将画面展示到surfaceView
try {
camera.setPreviewDisplay(sv_camera_surface.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int
height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
}
});
}
public void takePhoto(View view){
camera.takePicture(null, null, new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap bitmap=BitmapFactory.decodeByteArray(data,0,data.length);
//时间戳
Calendar calendar=Calendar.getInstance();
int year=calendar.get(Calendar.YEAR);
int month=calendar.get(Calendar.MONTH);
int day=calendar.get(Calendar.DAY_OF_MONTH);
try {
FileOutputStream fos=new FileOutputStream
("/mnt/sdcard/dcim/camera/G160628_"+year+(month+1)+day+"_"+System.currentTimeMillis
()+".jpg");
//压缩
bitmap.compress(Bitmap.CompressFormat.JPEG,85,fos);
camera.stopPreview();
camera.startPreview();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
}
}
最后配置:给它拍照的权限
<!--读取内容的权限-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<!--给手机内存写入内容的权限-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<!--给它拍照的权限-->
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
<!---给内存卡创建和删除的权限-->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>