2017-06-14 48 views
0

我试图缩小位图以将较小版本加载到内存中。我非常关注Google的示例(高效搜索加载大型位图),除了我从图库中加载而不是从资源加载。但是我似乎在计算维度之后找回空位图。这里是我的代码:尝试加载缩小版本时位图为空

/** OnActivityResult Method **/ 
    final Uri imageUri = data.getData(); 
    final InputStream imageStream = getActivity().getContentResolver().openInputStream(imageUri); 
    Bitmap bitmapToLoad = Util.decodeSampledBitmapFromResource(imageStream, 500, 500); // bitmapToLoad is null. 

    mIvScreenshot.setImageBitmap(bitmapToLoad); 


/**Helper Methods **/ 
    public static int calculateInSampleSize(
       BitmapFactory.Options options, int reqWidth, int reqHeight) { 
      // Raw height and width of image 
      final int height = options.outHeight; 
      final int width = options.outWidth; 
      int inSampleSize = 1; 

      if (height > reqHeight || width > reqWidth) { 

       final int halfHeight = height/2; 
       final int halfWidth = width/2; 

       // Calculate the largest inSampleSize value that is a power of 2 and keeps both 
       // height and width larger than the requested height and width. 
       while ((halfHeight/inSampleSize) >= reqHeight 
         && (halfWidth/inSampleSize) >= reqWidth) { 
        inSampleSize *= 2; 
       } 
      } 

      return inSampleSize; 
     } 

     public static Bitmap decodeSampledBitmapFromResource(InputStream is, 
                  int reqWidth, int reqHeight) { 
      Rect rect = new Rect(); 

      // First decode with inJustDecodeBounds = true to check dimensions 
      final BitmapFactory.Options options = new BitmapFactory.Options(); 
      options.inJustDecodeBounds = true; 
      BitmapFactory.decodeStream(is, rect, options); 

      // Calculate inSampleSize 
      options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 

      // Decode bitmap with inSampleSize set 
      options.inJustDecodeBounds = false; 
      return BitmapFactory.decodeStream(is, rect, options); 
     } 

任何人都可以抓住我做错了什么?

+0

你设法得到一个uri并打开输入流吗? (意思是没有空值也没有例外:final Uri imageUri = data.getData(); final InputStream imageStream = getActivity()。getContentResolver()。openInputStream(imageUri);? – Juan

+1

https://stackoverflow.com/a/13872663/ 833647您需要重置输入流,然后再阅读它“真实” –

回答

0

我设法让它工作。感谢Biraj Zalavadia(How to reduce an Image file size before uploading to a server)用于缩放逻辑,此处的游标代码(How to return workable filepath?)。这里是我的onActivityResult():

try { 
     final Uri imageUri = data.getData(); 

     String[] filePath = { MediaStore.Images.Media.DATA }; 
     Cursor cursor = getActivity().getContentResolver().query(imageUri, filePath, null, null, null); 
     cursor.moveToFirst(); 
     String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0])); 

     Uri newUri = Uri.parse(ScalingUtilities.scaleFileAndSaveToTmp(imagePath, 500, 500)); 

     final Bitmap selectedImage = BitmapFactory.decodeFile(newUri.getEncodedPath()); 
     mIvScreenshot.setImageBitmap(selectedImage); 
    } catch (Exception e) { 
     // Handle 
    } 
相关问题