decodeStream返回的bitmap为空问题

前言

在将图片加载到内存时,都要去做一个缩放,通过设置inJustDecodeBounds = true这样就只解析out属性,当我们要把options配置信息重新传给decodeStream时,返回的bitmap为空,这是因为inputStream被调用了两次,第二次已经清空。

解决方案

1.将输入流转为为字节数组。

  private byte[] inputStream2ByteArr(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buff)) != -1) {
            outputStream.write(buff, 0, len);
        }
        inputStream.close();
        outputStream.close();
        return outputStream.toByteArray();
    }

2.调用decodeByteArray来解析字节数组。

 byte[] inputStream2ByteArr = inputStream2ByteArr(inputStream);
                //TODO 网络上获取图片 模拟接收过程。

                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;

                BitmapFactory.decodeByteArray(inputStream2ByteArr,0,inputStream2ByteArr.length,options);

                int w = options.outWidth;
                int h = options.outHeight;

                options.inSampleSize = caculateInsampleSize(w,h,80,80);

                options.inJustDecodeBounds = false;

                options.inMutable =true;
                options.inBitmap = reusable;

                final Bitmap bitmap =  BitmapFactory.decodeByteArray(inputStream2ByteArr,0,inputStream2ByteArr.length,options);
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容