我需要将相机流转换为Bitmap并将其显示为ImageView。以下是CameraPreviewActivity的代码:
public class CameraPreviewActivity extends Activity {
private MyCamera myCamera;
private Camera camera;
private ImageView camView;
private Runnable r;
private Bitmap bm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myCamera = new MyCamera();
myCamera.startCamera();
camView = (ImageView) findViewById(R.id.camViewId);
setContentView(R.layout.camera_preview_layout);
getCameraFrameView();
}
private void getCameraFrameView() {
r = new Runnable() {
@Override
public void run() {
bm = myCamera.getCameraFrameBitmap();
if(bm != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
camView.setImageBitmap(bm);
}
});
}
}
};
r.run();
}
}
这是初始化并运行相机预览的类:
public class MyCamera {
private Camera mCamera = null;
private SurfaceTexture st = new SurfaceTexture(1);
private Bitmap cameraFrameBitmap;
private Camera.Parameters parameters;
private Camera.Size previewSize;
public void startCamera() {
Log.d("MyCamera", "Start Camera Initialized");
mCamera = Camera.open();
setupCameraParams();
try{
mCamera.setPreviewTexture(st);
mCamera.startPreview();
Log.d("MyCamera", "Camera Started Preview");
} catch (Exception e) {
e.printStackTrace();
}
}
private void setupCameraParams() {
if(mCamera != null) {
Log.d("MyCamera", "Setup Camera Params Started");
parameters = mCamera.getParameters();
List<Camera.Size> cameraSize = parameters.getSupportedPreviewSizes();
previewSize = cameraSize.get(0);
for(Camera.Size s : cameraSize) {
if((s.width * s.height) > (previewSize.height * previewSize.width)) {
previewSize = s;
}
}
parameters.setPreviewSize(previewSize.width, previewSize.height);
mCamera.setParameters(parameters);
mCamera.setPreviewCallback(previewCallback);
Log.d("MyCamera", "Setup Camera Done");
} else {
return;
}
}
private Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() {
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
if(parameters == null && previewSize == null) {
return;
}
try{
int format = parameters.getPreviewFormat();
YuvImage yuvImage = new YuvImage(data, format, previewSize.width, previewSize.height, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Rect rect = new Rect(0, 0, previewSize.width, previewSize.height);
yuvImage.compressToJpeg(rect, 100, baos);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPurgeable = true;
options.inInputShareable = true;
cameraFrameBitmap = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.size(), options);
baos.flush();
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
};
public Bitmap getCameraFrameBitmap() {
return cameraFrameBitmap;
}
}
这是正确的方法吗?还是有另一种方法将相机预览流式传输到ImageView作为位图?我的应用无法显示相框。我想在运行Runnable时可能会出现问题。我不习惯线程和 Runnable 。