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

來源:互聯網
上載者:User

標籤:非同步   圖片   

/**      * 根據指定的映像路徑和大小來擷取縮圖      * 此方法有兩點好處:      *     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;}}    }

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.