標籤:非同步 圖片
/** * 根據指定的映像路徑和大小來擷取縮圖 * 此方法有兩點好處: * 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 imageoptions.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;}} }
安卓非同步載入圖片(縮圖顯示)的實現