加载大位图失败

时间:2016-04-16 14:16:28

标签: java android bitmap

我在推荐的加载大位图的方法上遇到了问题。 我已经完全按照谷歌自己提供的指南。 但我无法让它工作,当我尝试将位图上传到我的后端时,我得到返回的位图为空:

  

java.lang.NullPointerException:尝试在空对象引用上调用虚方法'int android.graphics.Bitmap.getHeight()'

我可以上传未使用此方法创建的位图而不会出现任何问题,因此它肯定会在Bitmap创建中引发它。除了方法解码Stream而不是资源之外,我没有改变任何东西。

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 decodeBitmapFromStream(InputStream stream, Rect padding,
                                                     int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    //BitmapFactory.decodeResource(res, resId, options);
    BitmapFactory.decodeStream(stream,padding,options);

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

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

public void attachProfilePhoto(Uri uri){

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;


    InputStream stream;
    try {

        stream = getContentResolver().openInputStream(uri);

        Bitmap bitmap = decodeBitmapFromStream(stream,null,300,300);

        //Bitmap image_scaled = Bitmap.createScaledBitmap(bitmap, 500, 500 * bitmap.getHeight() / bitmap.getWidth(), false);

        uploadImage(bitmap, "image1");
        Picasso.with(this).load(uri).into(profile_image);


    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

0 个答案:

没有答案