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

Android 按指定大小讀取圖片的實(shí)例

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

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

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

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

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

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 讀取圖片大小顯示的問(wèn)題,有需要的朋友可以參考下。

相關(guān)文章

最新評(píng)論