[英]How do I convert raw camera data into a Bitmap on Android
我从库函数中获取byte[]
类型的原始相机数据rawData
,格式为 RGBA,大小为 640x480,每像素 4 个字节。 我需要将其转换为位图并显示在屏幕上的 ImageView 中。
我做的是以下内容:
byte[] JPEGData = convertToJpeg(rawData, 640, 480, 80);
Bitmap bitmap = BitmapFactory.decodeByteArray(JPEGData , 0, JPEGData .length);
imageView.setImageBitmap(bitmap);
其中convertToJpeg()
函数是:
public static byte[] convertToJpeg(byte[] buffer, int w, int h, int quality) {
YuvImage yuv_image = new YuvImage(buffer, ImageFormat.NV21, w, h, null);
Rect rect = new Rect(0, 0, w, h);
ByteArrayOutputStream output_stream = new ByteArrayOutputStream();
yuv_image.compressToJpeg(rect, quality, output_stream);
Bitmap sourceBmp = BitmapFactory.decodeByteArray(output_stream.toByteArray(), 0, output_stream.size());
Bitmap destBmp = Bitmap.createScaledBitmap(sourceBmp, (int) (w * 0.75), (int) (h * 0.75), true);
ByteArrayOutputStream pictureStream = new ByteArrayOutputStream();
destBmp.compress(CompressFormat.JPEG, quality, pictureStream);
byte[] pictureByteArray = pictureStream.toByteArray();
return pictureByteArray;
}
decodeByteArray()
调用后,我有bitmap.getConfig() == ARGB_8888
。
然而,我在屏幕上看到的是一些混乱的图片,原始图片中有一些模糊的绿色形状。
它出什么问题了?
事实证明,解决方案很简单。 并且无需转换为 JPEG。
Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bm.copyPixelsFromBuffer(ByteBuffer.wrap(rawData));
ByteBuffer().rewind 将缓冲区位置重置为 0,而不是解决了“缓冲区不足以容纳像素”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.