首页 文章

如何在android中调整图像的实际大小?

提问于
浏览
1

我的应用程序进入库,用户选择一个图像然后返回到我的活动中的onActivityResult方法,我获得了图像的文件路径 . 我可以通过实现以下方式获得位图的高度和宽度:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
int height = options.outHeight;
int width = options.outWidth;

现在,如果位图的宽度大于500像素,我需要调整图像的大小,使其最大宽度为500像素,并缩小高度 . 这是我将用于缩放高度的公式:

int origWidth = width;
        int origHeight = height;
        int destHeight, destWidth;

        if (origWidth <= 500 || origHeight <= 500) {
            destWidth = origWidth;
            destHeight = origHeight;
        } else {
            destWidth = 500;
            destHeight = (origHeight * destWidth) / origWidth;
        }

        Bitmap bitmap = BitmapFactory.create(/*bitmap source*/, 0, 0, destWidth, destHeight);

如何创建位图,因为inJustDecodeBounds属性设置为true,为位图对象返回null . 如果我将其设置为false,则选择大于内存所能容纳的图像将导致OutOfMemory错误 .

2 回答

  • 0

    使用Intent(“com.android.camera.action.CROP”)

    这是一个示例代码:

    Intent intent = new Intent("com.android.camera.action.CROP");
    // this will open all images in the Galery
    intent.setDataAndType(photoUri, "image/*");
    intent.putExtra("crop", "true");
    // this defines the aspect ration
    intent.putExtra("aspectX", aspectY);
    intent.putExtra("aspectY", aspectX);
    // this defines the output bitmap size
    intent.putExtra("outputX", sizeX);
    intent.putExtra("outputY", xizeY);
    // true to return a Bitmap, false to directly save the cropped iamge
    intent.putExtra("return-data", false);
    //save output image in uri
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    
  • 0

    如果图像的宽度> 500,请尝试使用以下代码段缩小图像 .

    public static Bitmap createScaledBitmap(Bitmap bitmap, int reqWidth) {
        if (bitmap.getWidth() > reqWidth) {
            int height = reqWidth / bitmap.getWidth() * bitmap.getHeight();
    
            Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, reqWidth, height, true);
            bitmap.recycle();
            return scaledBitmap;
        }
        return bitmap;
    }
    

相关问题