Java BitmapFactory.decodeByteArray() 返回 NULL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3338235/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:24:43  来源:igfitidea点击:

BitmapFactory.decodeByteArray() is returning NULL

javaandroidimageformatcamera

提问by RyoxSinfar

I am using the previewCallback from the camera to try and grab images. Here is the code I am using

我正在使用来自相机的 previewCallback 尝试抓取图像。这是我正在使用的代码

private Camera.PreviewCallback mPrevCallback = new Camera.PreviewCallback() 
{
        public void onPreviewFrame( byte[] data, Camera Cam ) {
                Log.d("CombineTestActivity", "Preview started");
                Log.d("CombineTestActivity", "Data length = " 
                        + data.length );
                currentprev = BitmapFactory.decodeByteArray( data, 0, 
                        data.length );

               if( currentprev == null )
                   Log.d("CombineTestActivity", "currentprev is null" );

                Log.d("CombineTestActivity", "Preview Finished" );

        }
};

the length of the data always comes otu the same as 576000.

数据的长度总是与 576000 相同。

Also I have tried changing the parameters of the camera so the image comes back as different formats. Here is what it looks like when I do that.

我还尝试更改相机的参数,以便图像以不同的格式返回。这是我这样做时的样子。

mCamera = Camera.open();
camParam = mCamera.getParameters();
camParam.setPreviewFormat( ImageFormat.RGB_565 );
mCamera.setParameters( camParam );
    mCamera.setPreviewCallback( mPrevCallback );

However both when I change the preview format and when I leave it as its default of NV21, BitmapFactory.decodeByteArray comes back as null. I have also tried changing the preview format to JPEG type. I even get a debug statement in the ddms, this is what I get

但是,无论是更改预览格式还是将其保留为默认的 NV21 时,BitmapFactory.decodeByteArray 都会返回为 null。我也尝试将预览格式更改为 JPEG 类型。我什至在 ddms 中得到了一个调试语句,这就是我得到的

"D/skia (14391): --- SkImageDecoder::Factory returned null"

“D/skia (14391): --- SkImageDecoder::Factory 返回 null”

回答by Chinasaur

I'm trying to do the same thing. Based on the discussions hereand here, it sounds like people have not had luck getting decodeByteArray()to handle NV21 format as of Android 2.1/2.2. It definitely doesn't work in my emulator or on my Droid Incredible, although I think this calls native code so it may work on some phones depending on the drivers?

我正在尝试做同样的事情。根据此处此处的讨论decodeByteArray(),从 Android 2.1/2.2开始,人们似乎没有运气处理 NV21 格式。它绝对不能在我的模拟器或我的 Droid Incredible 上运行,尽管我认为这会调用本机代码,因此它可能会在某些手机上运行,​​具体取决于驱动程序?

As an alternative, you can try to decode the NV21 yourself in Java (see link above for an example), although this is apparently too slow to be useful for most cases. I haven't had much luck trying to get CameraPreviewto send a different format either, and I would expect this to be problematic for trying to write code that is portable across different hardware. If you wrote the NV21 decode methods in NDK you might get the framerate up a bit.

作为替代方案,您可以尝试自己用 Java 解码 NV21(参见上面的链接示例),尽管这对于大多数情况来说显然太慢而无法使用。我也没有太多运气尝试CameraPreview发送不同的格式,并且我预计这对于尝试编写可跨不同硬件移植的代码来说是有问题的。如果您在 NDK 中编写了 NV21 解码方法,您可能会稍微提高帧率。

Apparently there are stability problems due to race conditions in trying to process the CameraPreviewtoo, although I haven't confirmed this issue myself. I think you might avoid this and also get your framerate up a bit by using the buffered preview callback method setPreviewCallbackWithBuffer()that was added in Android 2.1/2.2. This was added in 2.1 but was left hidden until 2.2. To use it in 2.1 you need to hack around the hiding.

显然,由于竞争条件在尝试处理时也存在稳定性问题CameraPreview,尽管我自己还没有确认这个问题。我认为您可以避免这种情况,并通过使用setPreviewCallbackWithBuffer()在 Android 2.1/2.2 中添加的缓冲预览回调方法来提高帧率。这是在 2.1 中添加的,但一直隐藏到 2.2。 要在 2.1 中使用它,您需要绕过隐藏。

Some people have suggested using MediaRecorderinstead of CameraPreview. Unfortunately, MediaRecorderappears to have even less provided for getting preview frames than CameraPreview, so I can't recommend that route.

有些人建议使用MediaRecorder代替CameraPreview. 不幸的是,MediaRecorder似乎比 提供的预览帧更少CameraPreview,所以我不能推荐这条路线。

回答by Qix - MONICA WAS MISTREATED

Alright, hopefully this will help.

好的,希望这会有所帮助。

Scoured the internet looking for a fast solution, and found the perfect thing.

在互联网上搜索快速解决方案,并找到了完美的解决方案。

This works as of Android 2.1

这适用于 Android 2.1

Thanks to off3nsiv3 from this page.

感谢来自此页面的off3nsiv3 。

// Convert to JPG
Size previewSize = camera.getParameters().getPreviewSize(); 
YuvImage yuvimage=new YuvImage(data, ImageFormat.NV21, previewSize.width, previewSize.height, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yuvimage.compressToJpeg(new Rect(0, 0, previewSize.width, previewSize.height), 80, baos);
byte[] jdata = baos.toByteArray();

// Convert to Bitmap
Bitmap bmp = BitmapFactory.decodeByteArray(jdata, 0, jdata.length);

Just a little modification to off3nsiv3's code and you're set. The FPS is still incredibly high compared to manual decoding.

只需对 off3nsiv3 的代码稍作修改即可。与手动解码相比,FPS 仍然非常高。

For the above code, the 80 is the jpeg quality (0 from 100, 100 being best).

对于上面的代码,80 是 jpeg 质量(0 来自 100,100 是最好的)。

回答by Chinasaur

Update from my earlier answer, but note Qix's answer, which looks simpler

从我之前的答案更新,但请注意 Qix 的答案,它看起来更简单

I've actually had decent results with decoding in pure Java. Framerates around 10-15 fps as long as the preview size is not too big. Sadly the Android 2.3 update to my Droid Inc seems to have taken away some of the smaller preview size options :(. I also tried doing it in native code that I pulled from another project, but this was buggy and didn't seem any faster for relatively simple processing I was doing, so I didn't pursue it further. See my Githubfor the source (both Java and native).

实际上,我用纯 Java 解码得到了不错的结果。只要预览尺寸不太大,帧率约为 10-15 fps。可悲的是,我的 Droid Inc 的 Android 2.3 更新似乎已经取消了一些较小的预览尺寸选项:(。我也尝试在我从另一个项目中提取的本机代码中执行此操作,但这是有问题的,并且似乎没有更快对于我正在做的相对简单的处理,所以我没有进一步研究。请参阅我的 Github以获取源代码(Java 和本机)。

回答by Hanly

try it like follow:

尝试如下:

    public Bitmap stringtoBitmap(String string) {
    Bitmap bitmap = null;
    try {
        YuvImage yuvimage = new YuvImage(base64.getBytes(),ImageFormat.YUY2, 120, 30, null);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        yuvimage.compressToJpeg(new Rect(0, 0, 20, 20), 100, baos);
        byte[] jdata = baos.toByteArray();
        bitmap = BitmapFactory.decodeByteArray(jdata, 0, jdata.length);
    } catch (Exception e) {

    }
    return bitmap;
}

回答by ROHIT PARMAR

you can try this and it is working...

你可以试试这个,它正在工作......

mCamera.setOneShotPreviewCallback(new Camera.PreviewCallback() {
                @Override
                public void onPreviewFrame(byte[] data, Camera camera) {
                    Camera.Parameters parameters = camera.getParameters();
                    int format = parameters.getPreviewFormat();
                    //YUV formats require more conversion
                    if (format == ImageFormat.NV21 || format == ImageFormat.YUY2 || format == ImageFormat.NV16) {
                        int w = parameters.getPreviewSize().width;
                        int h = parameters.getPreviewSize().height;
                        // Get the YuV image
                        YuvImage yuv_image = new YuvImage(data, format, w, h, null);
                        // Convert YuV to Jpeg
                        Rect rect = new Rect(0, 0, w, h);
                        ByteArrayOutputStream output_stream = new ByteArrayOutputStream();
                        yuv_image.compressToJpeg(rect, 100, output_stream);
                        byte[] byt = output_stream.toByteArray();
                        FileOutputStream outStream = null;
                        try {
                            // Write to SD Card
                            File file = createFileInSDCard(FOLDER_PATH, "Image_"+System.currentTimeMillis()+".jpg");
                            //Uri uriSavedImage = Uri.fromFile(file);
                            outStream = new FileOutputStream(file);
                            outStream.write(byt);
                            outStream.close();
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                        }
                    }
                }

回答by NagarjunaReddy

This is working for me...

这对我有用...

 private Camera.PreviewCallback getPreviewCallback() {
    Log.d("TAG", "previewCallBack ==> " + "getPreviewCallback");
    Camera.PreviewCallback previewBitmap = new Camera.PreviewCallback() {
        @Override
        public void onPreviewFrame(byte[] data, Camera camera) {
            Camera.Size previewSize = camera.getParameters().getPreviewSize();
            YuvImage yuvimage=new YuvImage(data, ImageFormat.NV21, previewSize.width, previewSize.height, null);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            yuvimage.compressToJpeg(new Rect(0, 0, previewSize.width, previewSize.height), 80, baos);
            byte[] jdata = baos.toByteArray();
            // Convert to Bitmap
            Bitmap bitmap = BitmapFactory.decodeByteArray(jdata, 0, jdata.length);
            Log.d("TAG", "BITMAP ==> " + bitmap);
            runModelInference(bitmap);
        }
    };

    return previewBitmap;
}