简体   繁体   English

如何在 Android 上将原始相机数据转换为位图

[英]How do I convert raw camera data into a Bitmap on Android

I obtain raw camera data rawData of type byte[] , format RGBA, size 640x480, 4 bytes per pixel, from a library function.我从库函数中获取byte[]类型的原始相机数据rawData ,格式为 RGBA,大小为 640x480,每像素 4 个字节。 And I need to convert it to a Bitmap and display in an ImageView on the screen.我需要将其转换为位图并显示在屏幕上的 ImageView 中。

What I do is the following:我做的是以下内容:

byte[] JPEGData = convertToJpeg(rawData, 640, 480, 80);
Bitmap bitmap = BitmapFactory.decodeByteArray(JPEGData , 0, JPEGData .length);    
imageView.setImageBitmap(bitmap);

where convertToJpeg() function is:其中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;
    }

After decodeByteArray() call I have bitmap.getConfig() == ARGB_8888 . decodeByteArray()调用后,我有bitmap.getConfig() == ARGB_8888

However, what I see on the screen is some chaotic picture, with some blurry green shapes of what's been in the original picture.然而,我在屏幕上看到的是一些混乱的图片,原始图片中有一些模糊的绿色形状。

What's wrong with it?它出什么问题了?

The solution has turned out to be simple.事实证明,解决方案很简单。 And no need to convert to JPEG.并且无需转换为 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM