我的应用程序进入库,用户选择一个图像然后返回到我的活动中的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 回答
使用Intent(“com.android.camera.action.CROP”)
这是一个示例代码:
如果图像的宽度> 500,请尝试使用以下代码段缩小图像 .