Unable to clearly convert camera to bitmap

2019-08-20 06:13发布

问题:

When I run the following bit of code on camera.setPreviewCallback, I get a static-y image. How can I get the ImageView (iv) to display correctly? Do I need to post more code here? Please be gentle as this is my first post on stackoverflow -- And, yes, I searched and searched, but didn't find anything, so if you find something that already asks the question, much thanks in advance.

YuvImage yuvImage = new YuvImage(data, ImageFormat.NV21, 300, 300, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
yuvImage.compressToJpeg(new Rect(0,0,300,300), 0, out);
byte[] imageBytes = out.toByteArray();
bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
iv.setImageBitmap(bitmap);

Oh, and yes, the ViewPort is 300x300.

I even tried this code:

int[] imageBytes = convertYUV420_NV21toRGB8888(data, 300, 300);
bitmap = Bitmap.createBitmap(300, 300, Bitmap.Config.ARGB_8888);
bitmap.setPixels(imageBytes, 0, 300, 0, 0, 300, 300);

which uses one of the functions on stackoverflow.

回答1:

I found the solution. The width and height were incorrect. Even though I had sized everything as 300x300, resolution issues caused that to not be the dimensions needed, so this code finally worked:

Camera.Parameters parameters = camera.getParameters();

YuvImage im = new YuvImage(data, ImageFormat.NV21, parameters.getPreviewSize().width, parameters.getPreviewSize().height, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
im.compressToJpeg(new Rect(0,0,parameters.getPreviewSize().width, parameters.getPreviewSize().height), 100, out);
byte[] imageBytes = out.toByteArray();
bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, out.size());
iv.setImageBitmap(bitmap);