Android中图片的缩放

在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);



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值