图片内存溢出处理

1.图片内存溢出

默认情况下,每个android程序的dailvik虚拟机的最大堆空间大小为16M
当加载的图片太多或图片过大时经常出现OOM问题
android 中用bitmap 时很容易内存溢出,报如下错误:Java.lang.OutOfMemoryError


2.解决办法

	public Bitmap matrixBitmapSize(Bitmap bitmap, int screenWidth,
			int screenHight) {
		//获取当前bitmap的宽高
		int w = bitmap.getWidth();
		int h = bitmap.getHeight();

		Matrix matrix = new Matrix();
		float scale = (float) screenWidth / w;
		float scale2 = (float) screenHight / h;

		// 取比例小的值 可以把图片完全缩放在屏幕内
		scale = scale < scale2 ? scale : scale2;

		// 都按照宽度scale 保证图片不变形.根据宽度来确定高度
		matrix.postScale(scale, scale);
		// w,h是原图的属性.
		return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
	}

	public Bitmap optionsBitmapSize(String imagePath, int screenWidth,
			int screenHight) {

		// 设置解析图片的配置信息
		BitmapFactory.Options options = new Options();
		// 设置为true 不再解析图片 只是获取图片的头部信息及宽高
		options.inJustDecodeBounds = true;
		// 返回为null
		BitmapFactory.decodeFile(imagePath, options);
		// 获取图片的宽高
		int imageWidth = options.outWidth;
		int imageHeight = options.outHeight;
		// 计算缩放比例
		int scaleWidth = imageWidth / screenWidth;
		int scaleHeight = imageHeight / screenHight;
		// 定义默认缩放比例为1
		int scale = 1;
		// 按照缩放比例大的 去缩放
		if (scaleWidth > scaleHeight & scaleHeight >= 1) {
			scale = scaleWidth;
		} else if (scaleHeight > scaleWidth & scaleWidth >= 1) {
			scale = scaleHeight;
		}
		// 设置为true开始解析图片
		options.inJustDecodeBounds = false;
		// 设置图片的采样率
		options.inSampleSize = scale;
		// 得到按照scale缩放后的图片
		Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
		return bitmap;
	}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值