开发者

Android 2.2 SDK - bitmap image resize nullPointerException

开发者 https://www.devze.com 2023-02-07 15:31 出处:网络
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 t

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 = 开发者_如何学CBitmap.createBitmap(bitmap, 0, 0, width, height,
                matrix, true);

        return new BitmapDrawable(resizedBitmap);
    }


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消