BitmapFactory.decodeStream returning null when options are set

前端 未结 4 455
北海茫月
北海茫月 2020-11-27 12:53

I\'m having issues with BitmapFactory.decodeStream(inputStream). When using it without options, it will return an image. But when I use it with options as in

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 13:07

    The problem was that once you've used an InputStream from a HttpUrlConnection to fetch image metadata, you can't rewind and use the same InputStream again.

    Therefore you have to create a new InputStream for the actual sampling of the image.

      Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
    
      BitmapFactory.decodeStream(is, null, options);
    
      Boolean scaleByHeight = Math.abs(options.outHeight - TARGET_HEIGHT) >= Math.abs(options.outWidth - TARGET_WIDTH);
    
      if(options.outHeight * options.outWidth * 2 >= 200*200*2){
             // Load, scaling to smallest power of 2 that'll get it <= desired dimensions
            double sampleSize = scaleByHeight
                  ? options.outHeight / TARGET_HEIGHT
                  : options.outWidth / TARGET_WIDTH;
            options.inSampleSize = 
                  (int)Math.pow(2d, Math.floor(
                  Math.log(sampleSize)/Math.log(2d)));
         }
    
            // Do the actual decoding
            options.inJustDecodeBounds = false;
    
            is.close();
            is = getHTTPConnectionInputStream(sUrl);
            Bitmap img = BitmapFactory.decodeStream(is, null, options);
            is.close();
    

提交回复
热议问题