根据路径获取图片,缩放图片

记录几个常用的图片相关操作方法;


根据路径获取图片,指定尺寸进行压缩
private Bitmap decodeThumbBitmapForFile(String path, int w, int h){
		BitmapFactory.Options opts = new BitmapFactory.Options();
		
		opts.inJustDecodeBounds = true;//
		opts.inPreferredConfig = Bitmap.Config.RGB_565; //如果不要求透明度可用此模式,更省内存
		
		//获取图片尺寸
		BitmapFactory.decodeFile(path, opts);
		int width = opts.outWidth;
		int height = opts.outHeight;
		float scaleWidth = 0.f, scaleHeight = 0.f;
		if (width > w || height > h) {
			//计算比例
			scaleWidth = ((float) width) / w;
			scaleHeight = ((float) height) / h;
		}
		
		opts.inJustDecodeBounds = false;//
		float scale = Math.max(scaleWidth, scaleHeight); //取较大或小数Math.min(,);
		//图片压缩比例,此数越大图片越小;(如为2,长宽都为原来的1/2,即图片为原图1/4份)
		opts.inSampleSize = (int)scale; //取整Math.ceil(scale)
		弱引用,更易被系统回收
		WeakReference<Bitmap> weak = new WeakReference<Bitmap>(BitmapFactory.decodeFile(path, opts));
		return Bitmap.createScaledBitmap(weak.get(), w, h, true);
	}


//另一种方式读取图片FileInputStream 
	public static Bitmap loadFromSdCard(String filePath) {
		File file = new File(filePath);
		Bitmap bmp = null;
		try {
			BitmapFactory.Options opts = new BitmapFactory.Options();
			
			opts.inJustDecodeBounds = false;
			opts.inPreferredConfig = Bitmap.Config.RGB_565;
			opts.inSampleSize = 2;
			FileInputStream fis = new FileInputStream(file);
			bmp = BitmapFactory.decodeStream(fis, null, opts);
			if(fis!=null){ 
			try {
				fis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}}
			if (bmp != null) {
				return bmp;
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}


将图片进行缩放
public static Bitmap scaleBitmap(Bitmap bmp, float newWidth, float newHeight) {

		if (bmp != null) {
	   int w= bm.getWidth();
  	   int h = bm.getHeight();
  	   // 计算比例
  	   float scaleWidth = ((float) newWidth) / w;
  	   float scaleHeight = ((float) newHeight) / h;
  	  
  	   Matrix matrix = new Matrix();
  	   matrix.postScale(scaleWidth, scaleHeight);	
			
			if (scaleWidth== 1.0f && scaleHeight== 1.0f) {
				return bmp;
			}

			Bitmap newbm = Bitmap.createBitmap(bmp, 0, 0, w,
					h, matrix, true);//
			return newbm;
	
		}
		return null;
	}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值