Android OnPreviewFrame 数据图像到 imageView
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20298699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
OnPreviewFrame data image to imageView
提问by Pitr
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()
我正在尝试从相机的预览中获取字节 [],将其转换为位图并使用 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.
我设法开始预览并将其显示在surfaceView上,但我不知道如何将字节[]数据(我认为是Yuv格式)转换为RGB位图以将其显示在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
预览有效,但 imageView 仍为空
Any idea?
任何的想法?
回答by blacelle
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:
您可能没有在 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);
}
});
}