SkImageDecoder::Factory returned null

最近在做大图片的加载,途中遇到这样一个问题:
图片在压缩文件中,我先用BitmapFactory取图片尺寸,计算之后再按照合适尺寸取出Bitmap,代码如下:
//...
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(imgInputStream, null, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(imgInputStream, null, options);
//...

图片死活就是显示不出来,log中
SkImageDecoder::Factory returned null

网上搜索了好多篇文章,都说的含糊其辞,于是看了SDK源代码:
在BitmapFactory.decodeStream中
    // we need mark/reset to work properly
    if (!is.markSupported()) {
        is = new BufferedInputStream(is, DECODE_BUFFER_SIZE);
    }
    // so we can call reset() if a given codec gives up after reading up to
    // this many bytes. FIXME: need to find out from the codecs what this
    // value should be.
    is.mark(1024);
    //...

于是看明白了,第一次取图片尺寸的时候is这个InputStream被使用过了,再真正取图片的时候又使用了这个InputStream,此时流的起始位置已经被移动过了,需要调用is.reset()来重置,然后再decodeStream(imgInputStream, null, options)就没问题了。
但是注意一个问题,is.mark(1024)是SDK中写死的,如果图片的大小超过1024字节,第一次decode取尺寸之后调用is.reset()会抛出IOException,所以建议使用BitmapFactory的其他decode方法,如果是网络读过来的流,最好在本地存成文件缓存,然后通过decodeFileDescriptor方法就没这种问题了。

猜你喜欢

转载自522656914.iteye.com/blog/1876181
今日推荐