尝试缩放图像并从android gallery返回位图

尝试缩放图像并从android gallery返回位图,android,image,bitmap,scale,decode,Android,Image,Bitmap,Scale,Decode,我目前正在从android gallery中提取一个图像,它将uri返回给活动进行预览,然后发送到解析数据库 发送的图像太大了,所以我实现了这些方法 这就是我的工作 Uri selectedImage = data.getData(); InputStream imageStream = getContentResolver().openInputStream(selectedImage); imageBitmap = getBitmapFrom

我目前正在从android gallery中提取一个图像,它将uri返回给活动进行预览,然后发送到解析数据库

发送的图像太大了,所以我实现了这些方法

这就是我的工作

Uri selectedImage = data.getData();
            InputStream imageStream = getContentResolver().openInputStream(selectedImage);

            imageBitmap = getBitmapFromReturnedImage(imageStream, 800, 800);

//                ByteArrayOutputStream stream = new ByteArrayOutputStream();
// LINE 2                imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
//                byte[] byteArray = stream.toByteArray();
//
//                parseFile = new ParseFile("location_image.jpg", byteArray);

            mImage.setImageBitmap(imageBitmap);



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 getBitmapFromReturnedImage(InputStream inputStream, int reqWidth, int reqHeight) {

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

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

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeStream(inputStream, null, options);
}
注释后的“第2行”,当该部分没有注释时,返回一个空指针异常,这让我大吃一惊。对该部分进行了注释后,当我运行应用程序时,imageview看起来只是空的


有什么线索吗?

在第二次调用decodeStream之前,您需要在读取边界后返回InputStream的开始,否则您将得到无效的位图。最简单的方法就是关闭流并再次打开它

请尝试以下代码(注意,函数不再是静态的,允许调用getContentResolver(),并且您传入的是Uri,而不是InputStream):

像这样打电话

Uri selectedImage = data.getData();
imageBitmap = getBitmapFromReturnedImage(selectedImage, 800, 800);

其他人也有同样的问题:谢谢你指出重复的内容。不知道为什么我在寻找的时候没有偶然发现。今天晚些时候我会试试这个。读起来很有道理。不过,让我想知道,为什么android官方文档会跳过这一点,分发不完整的代码?刚刚集成了这一点,它工作得完美无缺。谢谢@samgak
Uri selectedImage = data.getData();
imageBitmap = getBitmapFromReturnedImage(selectedImage, 800, 800);