Android:无法缩小位图对象

时间:2013-12-20 16:33:48

标签: android bitmap scale

以下代码取自Android开发人员,几乎没有变化:

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 decodeSampledBitmap(Bitmap bitmap, int reqWidth,
        int reqHeight) {

    int size = bitmap.getRowBytes() * bitmap.getHeight();
    InputStream is = new ByteArrayInputStream(new byte[size]);

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(is, null, options);
            // I set these manually because decodeStream set them to -1
    options.outHeight = bitmap.getHeight();
    options.outWidth = bitmap.getWidth();

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

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    // can the number of rows be wrong now?
    size = bitmap.getRowBytes() * options.outHeight;
    is = new ByteArrayInputStream(new byte[size]);
    return BitmapFactory.decodeStream(is, null, options);
}

我有两个问题:

  1. decodeStream中读取位图边界时,options.outHeight和options.outWidth都设置为-1,我不知道为什么
  2. 当从我设备的相机中取出位图时,公共方法返回null(因此从文件中读取),但是当从我手机上已存在的图像(从图库中选择)中获取位图时,该方法正常工作。
  3. 问题出在哪里?谢谢!

1 个答案:

答案 0 :(得分:0)

看起来图像已损坏或未正确保存。在将位图返回为null的错误情况下,这就是问题所在。

您可以通过将捕获的图像复制到桌面来检查桌面上图像查看器中的图像。