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

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


////根据路径获取图片,指定尺寸进行压缩
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 weak = new WeakReference(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;
	}



你可能感兴趣的:(Android)