先给大家看下效果图
我们用到一个SurfaceView来展示。具体我都写了注释。
package com.example.alarm_ontification;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private SurfaceView sv_main_surfaceview;
private Camera camera;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sv_main_surfaceview = (SurfaceView) findViewById(R.id.sv_main_surfaceview);
sv_main_surfaceview.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
camera = Camera.open();//开启照相机
Camera.Parameters parameters= camera.getParameters();// 给摄像头设置参数
parameters.setPictureFormat(PixelFormat.JPEG);// 设置照片的输出格式
parameters.set("jpeg-quality", 85);// 设置照片的质量
camera.setParameters(parameters);// 给照相机设置参数
try {
camera.setPreviewDisplay(sv_main_surfaceview.getHolder());//将摄像头的画面显示到SurfaceView控件上
camera.startPreview();//开启预览
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
}
});
}
public void opengo(View view){
//拍照
camera.takePicture(null, null, new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] bytes, Camera camera) {
Bitmap bitmap= BitmapFactory.decodeByteArray(bytes,0,bytes.length);
try {
FileOutputStream fos=new FileOutputStream("/mnt/sdcard/DCIM/camera/170223__"+System.currentTimeMillis()+".png");
bitmap.compress(Bitmap.CompressFormat.PNG,85,fos);
camera.stopPreview();
camera.startPreview();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
需要加入权限
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>