Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

android - OnPreviewFrame data image to imageView

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...