代码实现:
package com.zking.administrator.g160628_android28_playvideo;
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.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
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();
}
}
});
}
}