尝试加载缩小版本时,位图为null

时间:2017-06-14 15:54:25

标签: android

我试图缩小位图以将较小的版本加载到内存中。我非常关注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);
        }

任何人都可以抓住我做错的事吗?

1 个答案:

答案 0 :(得分: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
    }