1.首先android6.0以上版本要动态申请相机和文件读写权限
2.废话不啰嗦,上代码:
public class DistinguishActivity extends BaseActivity implements SurfaceHolder.Callback, Camera.PictureCallback {
private ImageView iv_ivPhoto;
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
private Camera camera;
List unGrantedPermissions;
private static final String[] MANDATORY_PERMISSIONS = {
"android.permission.CAMERA",
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE
};
private String localImgPath;
private LinearLayout guide_layout;
private TextView btn_preview;
private IPointToReadClient client;
private boolean isAuthorizatoned = false;
private final int TAKE_PICTURE = 0xa1;
private boolean camaraPouse = false;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case TAKE_PICTURE:
takePicture();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_distinguish);
initViews();
checkPermissions();
}
@Override
protected void onResume() {
super.onResume();
if (camaraPouse) {
initCamera();
}
}
private void checkPermissions() {
unGrantedPermissions = new ArrayList();
for (String permission : MANDATORY_PERMISSIONS) {
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
unGrantedPermissions.add(permission);
}
}
if (unGrantedPermissions.size() == 0) {//已经获得了所有权限
initCamera();
} else {//部分权限未获得,重新请求获取权限
String[] array = new String[unGrantedPermissions.size()];
ActivityCompat.requestPermissions(this, unGrantedPermissions.toArray(array), 0);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
unGrantedPermissions.clear();
for (int i = 0; i 0) {
for (String permission : unGrantedPermissions) {
if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
Toast.makeText(this, "权限" + permission + "被拒绝", Toast.LENGTH_SHORT).show();
finish();
} else ActivityCompat.requestPermissions(this, new String[]{permission}, 0);
}
} else {
initCamera();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
camera.release();
camera = null;
handler.removeMessages(TAKE_PICTURE);
}
private void initViews() {
surfaceView = (SurfaceView) findViewById(R.id.iv_surfaceview);
iv_ivPhoto = (ImageView) findViewById(R.id.iv_Photo);
btn_close = (ImageView) findViewById(R.id.btn_close);
btn_preview = (TextView) findViewById(R.id.btn_preview);
guide_layout = (LinearLayout) findViewById(R.id.guide_layout);
btn_preview.setOnClickListener(this);
showCamera();
}
private void initCamera() {
surfaceHolder = surfaceView.getHolder();
surfaceHolder.setFormat(PixelFormat.TRANSPARENT);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
surfaceHolder.setKeepScreenOn(true);//屏幕常亮
surfaceHolder.addCallback(this);
handler.sendEmptyMessageDelayed(TAKE_PICTURE, 1000);//2秒后自动拍照
}
private void takePicture() {
if (null != camera && null != client) {
camera.takePicture(null, null, null, DistinguishActivity.this);
Toast.makeText(DistinguishActivity.this,"=========拍照========",Toast.LENGTH_SHORT).show();
LogUtils.debugInfo("takePicture------------执行了拍照------------");
}
}
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
int cameraNums = Camera.getNumberOfCameras();
LogUtils.debugInfo("surfaceCreated------------" + cameraNums + "---------------");
try {
camera = Camera.open(cameraNums - 1);
camera.setPreviewDisplay(surfaceHolder);
Camera.Parameters parameters = camera.getParameters();
List sizeList = parameters.getSupportedPictureSizes();
int bestSize = 0;
for (Camera.Size size : sizeList) {
if (size.width == size.height) {
bestSize = size.width;
}
LogUtils.debugInfo("系统支持的尺寸-----------------------size.width=" + size.width + ";size.height=" + size.height);
}
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);//1连续对焦
if (bestSize == 0) {
parameters.setPictureSize(2976, 2976);//这个尺寸最接近1440*1440
} else {
parameters.setPictureSize(bestSize, bestSize);
}
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
parameters.set("orientation", "portrait");
camera.setDisplayOrientation(90);
parameters.setRotation(90);
}
List colorEffects = parameters.getSupportedColorEffects();
Iterator cei = colorEffects.iterator();
while (cei.hasNext()) {
String currentEffect = cei.next();
if (currentEffect.equals(Camera.Parameters.EFFECT_SOLARIZE)) {
parameters
.setColorEffect(Camera.Parameters.EFFECT_SOLARIZE);
break;
}
}
camera.setParameters(parameters);
camera.startPreview();
camera.cancelAutoFocus();// 2如果要实现连续的自动对焦,这一句必须加上
} catch (Exception e) {
// TODO Auto-generated catch block
LogUtils.debugInfo("Camera.open------------Exception------------" + e.getMessage());
Toast.makeText(DistinguishActivity.this, "相机打开失败", Toast.LENGTH_SHORT).show();
camera.release();
finish();
}
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
// //实现自动对焦
camera.autoFocus(new Camera.AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
if (success) {
camera.startPreview();
camera.cancelAutoFocus();//只有加上了这一句,才会自动对焦。
}
}
});
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
try {
camera.stopPreview();
camera.release();
}catch (RuntimeException e){
LogUtils.debugInfo("surfaceDestroyed------------------------RuntimeException="+e.getMessage());
}
}
@Override
public void onPictureTaken(byte[] bytes, Camera mcamera) {
LogUtils.debugInfo("onPictureTaken------------------------");
mcamera.startPreview();
BitmapFactory.Options options = new BitmapFactory.Options();
final Bitmap bitmap = getPicFromBytes(bytes, options);//byte转为bitmap原图
final Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 1440, 1440, true);//原图压缩为指定尺寸
final Bitmap result = setMatrix(scaledBitmap);//改变镜像
new Thread(new Runnable() {
@Override
public void run() {
//保存到本地
saveImageToGallery(result);
// 发起网络请求,上传图片到服务器
handler.sendEmptyMessageDelayed(TAKE_PICTURE, 50);//1秒后自动拍照
}
}).start();
}
private Bitmap getPicFromBytes(byte[] bytes,
BitmapFactory.Options opts) {
if (bytes != null)
if (opts != null)
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
opts);
else
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
return null;
}
private Bitmap setMatrix(Bitmap bmpPreview) {
Bitmap bitmap = null;
Matrix m = new Matrix();
m.postScale(-1, 1); // 镜像水平翻转
bitmap = Bitmap.createBitmap(bmpPreview, 0, 0, bmpPreview.getWidth(), bmpPreview.getHeight(), m, true);
return bitmap;
}
public int saveImageToGallery(Bitmap bmp) {
//生成路径
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
String dirName = "FingerReadingPhoto";
File appDir = new File(root, dirName);
if (!appDir.exists()) {
appDir.mkdirs();
}
String fileName = "TestPhoto.png";
localImgPath = appDir + "/" + fileName;
//获取文件
File file = new File(appDir, fileName);
if (file.exists()) {
file.delete();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
//通知系统相册刷新
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.fromFile(new File(file.getPath()))));
return 2;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return -1;
}
private void hideCamera() {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) surfaceView.getLayoutParams();
params.width = 1;
params.height = 1;
surfaceView.setLayoutParams(params);
}
private void showCamera() {
DisplayMetrics outMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
int widthPixels = outMetrics.widthPixels;
int heightPixels = outMetrics.heightPixels;
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) surfaceView.getLayoutParams();
params.width = widthPixels;
params.height = heightPixels;
surfaceView.setLayoutParams(params);
}
public void close(View view) {
if (action == 0) {
guide_layout.setVisibility(View.VISIBLE);
hideCamera();
} else {
finish();
}
}
}
作者:liaoff