在Android中,导入的图片尺寸太大,或者是图片体积过大,都会导致out of memory错误
解决的方法有很多种,其中比较简单的一种是预先读入图像的文件头,得到图像的尺寸大小,然后将他的尺寸和期望的尺寸进行对比,得到缩放系数,设置option参数,然后用该参数读取输入的图像,那么得到的图像就是缩小后的图像
具体代码如下:
BitmapFactory.Options opt = new BitmapFactory.Options();
// only read the header of file, not data 只读取文件头
opt.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(image_path, opt);
// 得到图片的尺寸
int picWidth = opt.outHeight;
int picHeight = opt.outHeight;
int screenWidth;
int screenHeight;
if (false) {
//acquire the height and width of window
WindowManager winManager = getWindowManager();
Display display = winManager.getDefaultDisplay();
screenWidth = display.getWidth();
screenHeight = display.getHeight();
} else {
//或者是设置指定的宽高
screenWidth = 800;
screenHeight = 600;
}
opt.inSampleSize = 1;
if (picWidth > picHeight) {
if (picWidth > screenWidth)
opt.inSampleSize = picWidth/screenWidth;
} else {
if (picHeight > screenHeight)
opt.inSampleSize = picHeight/screenHeight;
}
// 设置好缩放系数opt后,重新读取图像
opt.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(image_path, opt);