我正在尝试使用我的Android应用程序做一些非常不同的事情:我需要以定时间隔(每2秒左右)抓取相机的图像作为位图。我不想实时,因为我需要在位图上运行几个繁重的进程,为了提高效率,我不想每秒运行几十次。我也不需要将其保存为文件,我只需要在currentBitmap中使用它。
这是我试图实现它的代码:
public class MainActivity extends Activity {
private Camera camera;
private CameraPreview camPreview;
private FrameLayout camLayout;
// The app will process the camera frame on intervals instead of constantly
private static final long PROCESS_TIME = 2000; //(in milliseconds)
private static final long START_TIME = 2000;
private Timer timer;
// I want the bitmap in this instance
private Bitmap currentBitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
camLayout = (FrameLayout) findViewById(R.id.camera_preview);
setupCameraPreview();
// Set up the timer
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
TimerMethod();
}
}, START_TIME, PROCESS_TIME);
}
private void TimerMethod()
{ // Run Timer_Action on the same thread as the UI
this.runOnUiThread(Timer_Action);
}
private Runnable Timer_Action = new Runnable() {
public void run() {
// Process each bitmap here
try {
camera.takePicture(null, null, pictureCallback);
} catch (NullPointerException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),
"Photo capture attempted", Toast.LENGTH_SHORT).show();
}
};
private Camera.PictureCallback pictureCallback = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
try {
currentBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
Toast.makeText(getApplicationContext(),
"Photo capture successful", Toast.LENGTH_SHORT).show();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
};
private void setupCameraPreview() {
try { // Try to initialize the camera
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
camPreview = new CameraPreview(this, camera);
camLayout.addView(camPreview);
} catch (Exception e) {
e.printStackTrace();
camera = null;
camPreview = null;
}
}
当我跑步时发生的事情是相机预览和计时器似乎运行良好。但是pictureCallback,data []和currentBitmap都保持为null,因此try块会抛出异常并继续运行应用程序。我的猜测是pictureCallback没有从相机获取数据,但我该如何解决?如果这不是问题而不是什么?
非常感谢所有帮助。
答案 0 :(得分:0)
我不知道为什么pictureCallback没有正确初始化,我通常会将此回调声明为活动的一种方法,实现 Camera.PictureCallback和/或Camera.PreviewCallback。
但是出于您的目的,如果您对预览分辨率感到满意,可以通过计时器setOneShotPreviewCallback,或者只是在完成前一个缓冲区的处理时。
预览分辨率通常为640×480,而现代功能强大的设备则高达1080p。
在大多数手机和平板电脑上,回调只接收YUV图像,但有些可能配置为提供RGB。无论如何,yuv到rgb的转换应该不是问题(使用维基百科中的定点公式)。