OnPreviewFrame数据图像到imageView

时间:2013-11-30 09:37:41

标签: android bitmap android-camera yuv

我正在尝试从相机预览中获取byte [],将其转换为位图并使用imageView.setImageBitmap()

在imageview上显示

我已经设法开始预览并将其显示在surfaceView上,但我不知道如何在RGB位图中将byte []数据(我认为是Yuv格式)转换为在ImageView的。

我正在尝试的代码如下:

camera = camera.open();
parameters = camera.getParameters();
camera.setParameters(parameters);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
camera.setPreviewDisplay(surfaceHolder);
camera.setPreviewCallback(this);
camera.startPreview();

并且预览回调就是这个

@Override
public void onPreviewFrame(byte[] data, Camera camera) {

    Camera.Parameters parameters = camera.getParameters();
    int width = parameters.getPreviewSize().width;
    int height = parameters.getPreviewSize().height;
    ByteArrayOutputStream outstr = new ByteArrayOutputStream();
    Rect rect = new Rect(0, 0, width, height); 
    YuvImage yuvimage=new YuvImage(data,ImageFormat.NV21,width,height,null);
    yuvimage.compressToJpeg(rect, 100, outstr);
    Bitmap bmp = BitmapFactory.decodeByteArray(outstr.toByteArray(), 0, outstr.size());
    imgView1.setImageBitmap(bmp);        
}

预览有效,但imageView仍为空

有什么想法吗?

1 个答案:

答案 0 :(得分:25)

您可能没有在UI线程中打开相机。但是,您需要确保在UI线程中调用setImageBitmap:

@Override
public void onPreviewFrame(final byte[] data, Camera camera) {
    Camera.Parameters parameters = camera.getParameters();
    int width = parameters.getPreviewSize().width;
    int height = parameters.getPreviewSize().height;

    YuvImage yuv = new YuvImage(data, parameters.getPreviewFormat(), width, height, null);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    yuv.compressToJpeg(new Rect(0, 0, width, height), 50, out);

    byte[] bytes = out.toByteArray();
    final Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

    MyActivity.this.runOnUiThread(new Runnable() {

        @Override
        public void run() {
            ((ImageView) findViewById(R.id.loopback)).setImageBitmap(bitmap);
        }
    });
}