美文网首页
decodeStream返回的bitmap为空问题

decodeStream返回的bitmap为空问题

作者: remax1 | 来源:发表于2020-07-15 10:10 被阅读0次

前言

在将图片加载到内存时,都要去做一个缩放,通过设置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);

相关文章

网友评论

      本文标题:decodeStream返回的bitmap为空问题

      本文链接:https://www.haomeiwen.com/subject/ctcdhktx.html