BitmapFactory.decodeStream方法返回null的错误分析

本文介绍了一个关于BitmapFactory.decodeStream返回null的问题及解决方案。问题发生在使用Movie.decodeStream和BitmapFactory.decodeStream两次解码同一个InputStream时。解决方法是在第二次解码前将流的位置重置到起始位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在使用BitmapFactory.decodeStream解析is时,在is不为null的情况下BitmapFactory.decodeStream返回null。

异常如下:

这里写图片描述

代码如下:
private void obtainStyledAttr(Context context, AttributeSet attrs, int defStyleAttr) {
    TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.GifImageView, defStyleAttr, 0);
    int resId = getIdentifier(a);
    if (resId != 0) {
        // 当资源id不等于0时,就去获取该资源的流
        InputStream is = getResources().openRawResource(resId);
        // 使用Movie类对流进行解码
        mMovie = Movie.decodeStream(is);
        //mMovie不等null说明这是一个GIF图片
        if (mMovie != null) {
            //是否自动播放
            isAutoPlay = a.getBoolean(R.styleable.GifImageView_auto_play, false);
            /**
             * 获取gif图片大小
             */
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            bitmapSize = new BitmapSize(bitmap.getWidth(), bitmap.getHeight());
            bitmap.recycle();
        }
    }
    a.recycle();
}
异常原因:

decodeStream调用了两次

  • Movie类先对is进行了解码,代码如下:

// 使用Movie类对流进行解码
mMovie = Movie.decodeStream(is);

  • 然后BitmapFactory又对is进行了解码,代码如下:

Bitmap bitmap = BitmapFactory.decodeStream(is);

第一次decodeStream时已经操作过inputstream了,这时候流的操作位置已经移动了,如果再次decodeStream则不是从流的起始位置解析,所以无法解析出Bitmap对象。

解决方法:

只需要在再次解码之前使流读写位置恢复为起始位置即可,代码如下:

private void obtainStyledAttr(Context context, AttributeSet attrs, int defStyleAttr) {
    TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.GifImageView, defStyleAttr, 0);
    int resId = getIdentifier(a);
    if (resId != 0) {
        // 当资源id不等于0时,就去获取该资源的流
        InputStream is = getResources().openRawResource(resId);
        // 使用Movie类对流进行解码
        mMovie = Movie.decodeStream(is);
        //mMovie不等null说明这是一个GIF图片
        if (mMovie != null) {
            //是否自动播放
            isAutoPlay = a.getBoolean(R.styleable.GifImageView_auto_play, false);
            /**
             * 获取gif图片大小
             */
            try {
                is.reset();
                Bitmap bitmap = BitmapFactory.decodeStream(is);
                bitmapSize = new BitmapSize(bitmap.getWidth(), bitmap.getHeight());
                bitmap.recycle();
            } catch (Exception e) {
                Log.e("yushan", "" + e);
            }
        }
    }
    a.recycle();
}

参考链接:
https://blog.youkuaiyun.com/maxwell_nc/article/details/49081105

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值