首页 > 解决方案 > 使用字节数组初始化时位图返回 null

问题描述

我有位图,我正在使用代码分配一个字节数组值:

public class LegacyCameraManager implements Camera.ErrorCallback, Camera.PreviewCallback, Camera.AutoFocusCallback, Camera.PictureCallback {
public static Bitmap mBitmap;
    @Override
    public void onPreviewFrame(byte[] bytes, Camera camera) {
        Boolean isProcessing = UserSharedPref.initializeSharedPreferencesForprocessFrames(mContext).getBoolean(UserSharedPref.processFrames, true);
        if (isProcessing) {
            Log.d("TEST:","length of bytes:"+bytes.length);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            mBitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length,options);
            Log.d("TEST:","The bitmap:"+mBitmap);
            tfDetector.onPreviewFrame(bytes, camera);

        }
    }

其余的代码运行良好,并且这个方法被连续调用,问题是 mBitmap 总是注销为“null”,这个变量必须设置为这样的图像视图,像这样的按钮的 onclikc:

 if (LegacyCameraManager.mBitmap == null) {
            Log.d("TEST:","Bitmaps is NULL!!");
            img.setImageResource(R.drawable.office);
        } else {
            img.setImageBitmap(Bitmap.createScaledBitmap(LegacyCameraManager.mBitmap, img.getWidth(),
                    img.getHeight(), false));
        }

Logcat(应该有很多次): length of bytes:460800 The bitmap:null

因此,图像没有被设置为位图为空,实际功能是将图像视图设置为在位图被分配的那一刻拍摄的照片,就像它应该的那样。我哪里错了?

标签: javaandroidarraysandroid-bitmap

解决方案


试试这个:

Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);

返回解码的位图,如果图像无法解码,则返回 null。


推荐阅读