【问题标题】:Android 2.2 SDK - bitmap image resize nullPointerExceptionAndroid 2.2 SDK - 位图图像调整大小 nullPointerException
【发布时间】:2011-02-01 00:32:20
【问题描述】:

我正在从不同大小的 URL 加载图像。似乎较小的通过了,而较大的则通过了 nullPointerException(显示在下面的 Log.d 中)。如何让这些图像调整大小?

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

这是我用来从 URL 加载的内容:

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

        return bitmap;
    }

这是我用来调整大小的,出现错误的地方:

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

【问题讨论】:

  • 你能再具体一点吗?你的 NPE 扔到哪里去了?电话号码?哪一行代码?

标签: android mobile bitmap android-2.2-froyo


【解决方案1】:

为什么不使用可用的位图功能来调整大小。假设您下载了正确的图像,您只需要执行以下操作:

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

【讨论】:

    猜你喜欢
    • 2015-06-04
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    相关资源
    最近更新 更多