安卓Camera对象获取方式
Camera c = Camera.open(0);//1,0代表前后摄像头
c.setDisplayOrientation(90);//预览图与手机方向一致
SurfaceView surfaceView = findViewById(R.id.surfaceView1);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
//启动预览,到这里就能正常预览
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
public void surfaceCreated(SurfaceHolder holder) {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview(); //开始预览
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
public void surfaceDestroyed(SurfaceHolder holder) {
}
});
//获取摄像实时数据
camera.setPreviewCallback(new Camera.PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera camera) {
Camera.Size size = camera.getParameters().getPreviewSize();
try{
YuvImage image = new YuvImage(data, ImageFormat.NV21, size.width, size.height, null);
if(image!=null){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compressToJpeg(new Rect(0, 0, size.width, size.height ), 100, stream);//jpg图片数据size.width, size.height
//此时stream中是一张jpg图片字节数组,可直接使用
Bitmap bm = BitmapFactory.decodeByteArray(stream.toByteArray(),0,stream.size());//转位图
stream.close();
}
}catch(Exception ex){
Log.e("Sys","Error:"+ex.getMessage());
}
}
});
位图Bitmap旋转
//旋转位图
public Bitmap roteBitmap(Bitmap bitmap){
Matrix mx = new Matrix();
mx.postRotate(90);//旋转角度
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(),bitmap.getHeight(),true);
Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap,0,0,scaledBitmap.getWidth(), scaledBitmap.getHeight(),mx,true);//旋转后的位图
return rotatedBitmap;
}
位图转jpg图片字节数组
//位图转换字节数组
public byte[] BitmipToBytes(Bitmap bitmap){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
return stream.toByteArray();
}
需要权限
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.Camera.autofocus"/>