从BufferedInputStream调整联系人图像

时间:2016-08-19 18:41:06

标签: android bitmap inputstream

我正在尝试检查已获取的联系人图片的大小,并在需要时调整大小。我正在使用官方开发人员android网站模式https://developer.android.com/training/displaying-bitmaps/load-bitmap.html的建议,并进行了一些小的更改。这是我的代码

private 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 decodeSampledBitmapFromBufferedStream(BufferedInputStream bufferedInputStream,
                                                     int reqWidth, int reqHeight) throws IOException
{
    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;

    // Calculate inSampleSize
    BitmapFactory.decodeStream(bufferedInputStream, new Rect(), options);
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeStream(bufferedInputStream, new Rect(), options);
}

我从游标内部调用decodeSampledBitmapFromBufferedStream方法(我真的不知道它是否重要)。我的问题是选项对象的outHeight和outwidth始终为0,返回位图为null。我认为这与重新使用bufferedInoutStream对象有关,但我不知道如何解决它。提前谢谢。

1 个答案:

答案 0 :(得分:0)

一旦它的位置移动了流,你通常无法返回(除非它有一个倒带方法,如文件流)。您可以关闭流,然后打开一个新流,或者第一次将完整流读入字节数组,然后两次使用decodeByteArray