Android 2.2 SDK - bitmap image resize nullPointerException

2.3k views Asked by At

I'm loading images from URLS that are varying sizes. It seems the smaller ones come through, and a nullPointerException (displayed in the Log.d below) comes through for the larger ones. How can I get these images to resize?

                BitmapDrawable drawable = null;
                Bitmap bitmap = null;
                try {
                    bitmap = loadBitmapFromWeb(url);
                    System.out.println("url " + url);
                } catch (IOException e) {
                }

                int width = 150;
                int height = 150;
                try {
                    drawable = resizeImage(bitmap, height, width);
                } catch (Exception e) {
                    Log.d("exception image", e.toString());
                    drawable = getDrawableFromResource(R.drawable.default_backup);
                }

This is what I use to load from a URL:

    public static Bitmap loadBitmapFromWeb(String url) throws IOException {
        InputStream is = (InputStream) new URL(url).getContent();
        Bitmap bitmap = BitmapFactory.decodeStream(is);

        return bitmap;
    }

This is what I use to resize, where the error appears:

    public static BitmapDrawable resizeImage(Bitmap bitmap, int w, int h) {

        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int newWidth = w;
        int newHeight = h;

        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);

        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height,
                matrix, true);

        return new BitmapDrawable(resizedBitmap);
    }
1

There are 1 answers

0
Zelimir On

Why don't you use available Bitmap function to do the resize. Supposing you downloaded correct image, you just need to do the following:

    Bitmap scaledImage = Bitmap.createScaledBitmap(originalImage, newWidth, newHeight, false);