1. 程式人生 > >安卓非同步載入圖片(縮圖顯示)的實現

安卓非同步載入圖片(縮圖顯示)的實現

/** 
     * 根據指定的影象路徑和大小來獲取縮圖 
     * 此方法有兩點好處: 
     *     1. 使用較小的記憶體空間,第一次獲取的bitmap實際上為null,只是為了讀取寬度和高度, 
     *        第二次讀取的bitmap是根據比例壓縮過的影象,第三次讀取的bitmap是所要的縮圖。 
     *     2. 縮圖對於原影象來講沒有拉伸,這裡使用了2.2版本的新工具ThumbnailUtils,使 
     *        用這個工具生成的影象不會被拉伸。 
     * @param imagePath 影象的路徑 
     * @param width 指定輸出影象的寬度 
     * @param height 指定輸出影象的高度 
     * @return 生成的縮圖 
     */  
    private void getImageThumbnail(ImageView thumbnails_img,String imagePath,int width,int height) {  
    	asy = new AsyncImageTask(thumbnails_img,width,height);
    	asy.execute(imagePath);
    }
    /**
     * 使用非同步執行緒載入圖片
     * 執行緒池
     */
    private final class AsyncImageTask extends AsyncTask<String,Integer,Bitmap>{
    	private ImageView thumbnails_img;
    	private int width;
    	private int height;
    	
		public AsyncImageTask(ImageView thumbnails_img,int width, int height) {
			this.thumbnails_img = thumbnails_img;
			this.width = width;
			this.height = height;
		}

		protected Bitmap doInBackground(String... params) {
			
			img_bitmap = null;
			//節約記憶體
			options.inPreferredConfig = Bitmap.Config.ARGB_4444;/*設定讓解碼器以最佳方式解碼*/
			options.inPurgeable = true;
			options.inInputShareable = true;
			options.inJustDecodeBounds = true;  
			//If diTher is true, the decoder will attempt to dither the decoded image
			options.inDither = false;//不進行圖片抖動處理
			// 獲取這個圖片的寬和高,注意此處的bitmap為null  
			img_bitmap = BitmapFactory.decodeFile(params[0], options);
			options.inJustDecodeBounds = false;//設為 false 
			
			//計算縮放比
			int h = options.outHeight;  
			int w = options.outWidth;  
			int beWidth = w / width;  
			int beHeight = h / height;  
			int be = 1;  
			if (beWidth < beHeight) {  
				be = beWidth;  
			} else {  
				be = beHeight;  
			}  
			if (be <= 0) {  
				be = 1;  
			}
			options.inSampleSize = be;  
			// 重新讀入圖片,讀取縮放後的bitmap,注意這次要把options.inJustDecodeBounds 設為 false  
			img_bitmap = BitmapFactory.decodeFile(params[0], options);  
			// 利用ThumbnailUtils來建立縮圖,這裡要指定要縮放哪個Bitmap物件  
			
			img_bitmap = ThumbnailUtils.extractThumbnail(img_bitmap, width, height,  
					ThumbnailUtils.OPTIONS_RECYCLE_INPUT);  
			
			return img_bitmap;
		}
		//處理結果
		protected void onPostExecute(Bitmap result) {
			if(result!=null&&thumbnails_img != null){
				thumbnails_img.setImageBitmap(result);
				asy_list.add(asy);
				
				asy = null;
//				img_bitmap.recycle();
			    img_bitmap=null;
			}
		}
    }