Android开发中调用到摄像头camera及截图。通过测试发现,调用前置摄像头的预览图和截图、调用后置摄像头的预览图和截图,参数是不一样的。
调用前置摄像头:
camera = Camera.open(1);
camera.setDisplayOrientation(90);//正常预览。如果参数设为270度,则预览图像为倒置。
onPreviewFrame()中调用bitmapRotated = utils.PicProcessUtils.rotaingImageView(270, bmp);//参数270度,截图为正常图。90度截图是倒置的。
调用后置摄像头:
camera = Camera.open(0);
camera.setDisplayOrientation(90);//正常预览。如果参数设为270度,则预览图像为倒置。
onPreviewFrame()中调用bitmapRotated = utils.PicProcessUtils.rotaingImageView(90, bmp);//参数90度,截图为正常图。270度截图是倒置的
详细代码如下:
private void preview() throws IOException {
if (hasFrontFacingCamera()) {//如果有前置摄像头
camera = Camera.open(1);
} else {
camera = Camera.open(0);
}
camera.setDisplayOrientation(90);
Camera.Parameters params = camera.getParameters();
List sizes = params.getSupportedPreviewSizes();
Camera.Size selected = sizes.get(1);
width = selected.width;
height = selected.height;
params.setPreviewSize(640, 480);
// params.setPictureFormat(PixelFormat.RGB_565);
// params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
// params.setPreviewSize(width, height);
camera.setParameters(params);
camera.setPreviewDisplay(holder);
camera.startPreview();
}
@Override
public void onPreviewFrame(byte[] data, Camera arg1) {
// TODO Auto-generated method stub
Log.e(TAG, "onPreviewFrame");
Camera.Size size = camera.getParameters().getPreviewSize();
final int w = size.width;
final int h = size.height;
final YuvImage image = new YuvImage(data, ImageFormat.NV21, w, h, null);
ByteArrayOutputStream os = new ByteArrayOutputStream(data.length);
System.out.println("in2");
if (!image.compressToJpeg(new Rect(0, 0, w, h), 100, os)) {
return;
}
// System.out.println("out1");
byte[] tmp = os.toByteArray();
Bitmap bmp = BitmapFactory.decodeByteArray(tmp, 0, tmp.length);
// doSomethingNeeded(bmp); //自己定义的实时分析预览帧视频的算法
if(hasFrontFacingCamera()) {
bitmapRotated = utils.PicProcessUtils.rotaingImageView(270, bmp);//前置摄像头270度,后置摄像头90度
} else {
bitmapRotated = utils.PicProcessUtils.rotaingImageView(90, bmp);
}
// iv[i].setImageBitmap(bmp1);
System.out.println("out2");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapRotated.compress(Bitmap.CompressFormat.JPEG, 80, stream);
tmp = stream.toByteArray();
// doSomethingNeeded(bmp);
Log.e("frameIndex=", frameIndex + "");
if (frameIndex < 2) {
use[frameIndex] = tmp;
frameIndex++;
}
System.out.println("out3");
return;
}
public static Bitmap rotaingImageView(int angle , Bitmap bitmap) {
//旋转图片 动作
Matrix matrix = new Matrix();;
matrix.postRotate(angle);
System.out.println("angle2=" + angle);
// 创建新的图片
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return resizedBitmap;
}
相关文章android camera 通过onPreviewFrame采集视频
Android系统Camera图片反转的一个问题
解决android有的手机拍照后上传图片被旋转的问题