OnPreviewFrame data image to imageView

元气小坏坏 提交于 2019-12-28 12:44:13

问题


i'm trying to get the byte[] from the preview of the camera, convert it to bitmap and display it on a imageview with imageView.setImageBitmap()

i've managed to start the preview and display it on a surfaceView, but i don't know how to convert the byte[] data (that comes in Yuv format i think) in a RGB bitmap to display it on a imageView.

the code i'm trying is the following:

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();

and the preview callback is this

@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);        
}

The preview works but the imageView remains empty

Any idea?


回答1:


It is possible you did not open the Camera in the UI thread. However, you need to ensure setImageBitmap is called in the UI thread:

@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);
        }
    });
}


来源:https://stackoverflow.com/questions/20298699/onpreviewframe-data-image-to-imageview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!