欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android 按指定大小讀取圖片的實例

 更新時間:2016年07月13日 15:47:29   投稿:lqh  
本文主要介紹Android 按指定大小讀取圖片,在Android開發(fā)過程中經(jīng)常會遇到圖片超過屏幕,或者圖片過小問題,這里給一個實例解決讀取圖片大小的問題,希望能幫助有需要的小伙伴

在Android開發(fā)中,我們經(jīng)常遇到Android讀取圖片大小超過屏幕顯示的圖(一般只要顯示一定規(guī)格的預覽圖即可),在圖片特別多或者圖片顯示很頻繁的時候要特別注意這個問題,下面介紹個按指定大小讀取圖像的方法。

實現(xiàn)原理:首先獲取圖片文件的圖像高和寬,如果小于指定比例,則直接讀??;如果超過比例則按指定比例壓縮讀取。

捕獲OutOfMemoryError時注意點:后面返回的是null,不要馬上從別的地方再讀圖片,包括R文件中的,不然依然會拋出這個異常,一般在初始化的時候緩存默認圖片,然后顯示緩存中的圖片。

/** 獲取圖像的寬高**/

public static int[] getImageWH(String path) {
	int[] wh = {-1, -1};
 if (path == null) {
 	return wh;
 }
 File file = new File(path);
 if (file.exists() && !file.isDirectory()) {
  try {
   BitmapFactory.Options options = new BitmapFactory.Options();
   options.inJustDecodeBounds = true;
   InputStream is = new FileInputStream(path);
   BitmapFactory.decodeStream(is, null, options);
   wh[0] = options.outWidth;
   wh[1] = options.outHeight;
  }
  catch (Exception e) {
   Log.w(TAG, "getImageWH Exception.", e);
  }
 }
 return wh;
}
 
public static Bitmap createBitmapByScale(String path, int scale) {
	Bitmap bm = null;
 try {
 	//獲取寬高
  int[] wh = getImageWH(path);
  if (wh[0] == -1 || wh[1] == -1) {
  	return null;
  }

  //讀取圖片
  BitmapFactory.Options options = new BitmapFactory.Options();
  options.inSampleSize = Math.max(wh[0]/scale, wh[1]/scale);
  InputStream is = new FileInputStream(path);
  	bm = BitmapFactory.decodeStream(is, null, options);
 }
 catch (Exception e) {
 	Log.w(TAG, "createBitmapByScale Exception.", e);
 }
 catch (OutOfMemoryError e) {
  Log.w(TAG, "createBitmapByScale OutOfMemoryError.", e);
  //TODO: out of memory deal..
 }
 return bm;
}

以上就是解決Android 讀取圖片大小顯示的問題,有需要的朋友可以參考下。

相關文章

最新評論