【问题标题】:How to scale down a bitmap image before loading into an imageview?如何在加载到图像视图之前缩小位图图像?
【发布时间】:2014-12-31 22:24:00
【问题描述】:

我正在使用以下方法从 Android 图库加载图像,它可以工作,但如果我选择使用后置摄像头拍摄的图像(即大分辨率),它不会加载到图像视图中。它会从前置摄像头加载较小的图像而不会失败。

我猜图像需要按比例缩小才能成功加载到图像视图中。

有人知道如何以编程方式缩小图像吗?

我已将createScaledBitmap 代码行注释掉,因为我不确定如何实现它。

这是从图库中获取图像的完整方法:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            if(data != null){
            ImageView imageView = (ImageView) findViewById(R.id.capturedDebriImageView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
            //imageView.setImageBitmap(Bitmap.createScaledBitmap(picturePath, 130, 110, false));
            }
            else if(data == null){
                 Toast.makeText(this, "Callout for image failed!", 
                         Toast.LENGTH_LONG).show();

            }


        }
    }

【问题讨论】:

  • 用你的代码运行注释掉的行
  • @RobertRowntree 我已经厌倦了它,但picturePath 是一个不适用于构造函数的字符串。我收到以下错误:The method createScaledBitmap(Bitmap, int, int, boolean) in the type Bitmap is not applicable for the arguments (String, int, int, boolean)

标签: android image bitmap scale


【解决方案1】:

其实还有更高效的方法:

BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = (int) scaleFactor;
inputStream = getContentResolver().openInputStream(uri);
Bitmap scaledBitmap = BitmapFactory.decodeStream(inputStream, null, bitmapOptions);

这样可以避免“临时”位图对象,而是立即加载已经缩小的版本。

【讨论】:

    【解决方案2】:

    您需要将图像加载到一个位图中,然后从第一个位图创建第二个按比例缩小的位图:

    Bitmap bmp = BitmapFactory.decodeFile(picturePath);
    imageView.setImageBitmap(Bitmap.createScaledBitmap(bmp, 130, 110, false));
    bmp.recycle();
    

    此方法允许您将位图缩放到任意宽度和高度。如果您不需要它的精确大小,那么按照其他答案使用 inSampleSize 会更有效,但您只能按 2 的幂进行缩放。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多