Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 圖片處理實戰:用 AsyncTask 與回呼介面打造非同步載入與壓縮流程

編輯:關於 Android 程式設計

在前面一篇文章中,我們談過如何借助軟參照(SoftReference)為圖片建立高速快取。然而要處理圖片,第一步得先解決「圖片從哪裡來」的問題。一般來說,App 內的圖片資源大多來自伺服器。本文就沿用先前封裝好的 httpUtils,把遠端圖片下載到本機,再與軟參照快取搭配使用,並以 ListView 作為示範場景。

一、前置準備

動手之前,我們需要準備好幾個類別(圖片物件與軟參照快取類別請參考上一篇):

1、圖皮下載類別 ImageDownload
2、圖皮下載工具 FreedomHttpClientUtil(參考 HttpClient 檔案上傳下載相關章節)
3、非同步處理任務 LoadTask
4、回呼介面 FreedomCallBack

二、工具類別的實作

1、先定義回呼介面

 public interface FreedomCallback { /** * @Title: imageLoaded * @Description: TODO * @param imageDrawable 傳回的bitmap對象 * @param tag 用於listView查找控件 * @throws */ public void imageLoaded(Bitmap imageDrawable, Object tag); }

2、圖皮下載類別與非同步任務

我們把非同步下載任務設計成圖皮下載類別的內部類別,讓職責更集中。

 public class ImageDownload { private static final String TAG = "ImageDownload"; private static String path; //構建緩存地址 static { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { File externalStorageDirectory = Environment .getExternalStorageDirectory(); path = externalStorageDirectory.getAbsolutePath() + ConstantValue.IMAGE_PATH; File directory = new File(path); if (!directory.exists()) { directory.mkdirs(); } } else { path = null; Log.e(TAG, "no sdcard."); } } /** * @Title: loadDrawable * @Description: 下載圖片 * @param imageUrl * @param simpleName * @param imageCallback * @throws */ public void loadDrawable(String imageUrl, String simpleName, FreedomCallback imageCallback) { new FreedomLoadTask(imageCallback).execute(imageUrl, simpleName); } /** * @Title: loadImageFromUrl * @Description: 根據地址下載圖片 * @param url * @return * @throws */ public Bitmap loadImageFromUrl(String url) { InputStream i = null; try { FreedomHttpClientUtil util = new FreedomHttpClientUtil(); util.open(url, FreedomHttpClientUtil.GET); util.post(); i = util.openInputStream(); //拿到流後創建bitmap Bitmap bitmap = BitmapFactory.decodeStream(i); return bitmap; } catch (Exception e) { e.printStackTrace(); } return null; } /** * @Title: saveImage2SDCard * @Description: 將圖片存放到SD卡中 * @param simpleName * @param bitmap * @throws */ public void saveImage2SDCard(String simpleName, Bitmap bitmap) { if (StringUtils.isNotBlank(path)) { File file = new File(new File(path), simpleName + ".png"); FileOutputStream fOut = null; try { fOut = new FileOutputStream(file); //將bitmap寫入流中 bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut); fOut.flush(); } catch (Exception e) { org.cao.optimization.util.Log.info("文件無法創建"); e.printStackTrace(); } finally { if (fOut != null) try { fOut.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * @ClassName: FreedomLoadTask * @author victor_freedom (x_freedom_reddevil@126.com) * @createddate 2015-1-31 下午11:39:18 * @Description: 圖片下載,返回一個bitmap對象 */ class FreedomLoadTask extends AsyncTask { private FreedomCallback imageCallback; public FreedomLoadTask(FreedomCallback imageCallback) { this.imageCallback = imageCallback; } @Override protected Bitmap doInBackground(String... params) { // 傳入兩個 參數,一個是下載路徑,一個是文件名稱 Bitmap bitmap = loadImageFromUrl(params[0]); if (bitmap != null) { // 保存到SD卡中 saveImage2SDCard(params[1], bitmap); // 加入緩存中 ImageCache.getInstance().cacheImage( new Image(params[1], bitmap)); } return bitmap; } @Override protected void onPostExecute(Bitmap result) { // 下載成功後執行回調接口 imageCallback.imageLoaded(result, null); super.onPostExecute(result); } } }

三、介面層的處理

1、在 Adapter 的 getView 中著手

這裡假設每個項目只有一個 ImageView,並以 ViewHolder 做效能優化。getView 的邏輯可以這樣安排:先查快取,快取沒有就查本機檔案,本機也沒有才向伺服器下載。

 //拿到圖片的名字 final String id = infos.getName(); //給此處ImageView空間設置id continer.image.setTag(id); //根據名字首先從軟應用中拿到bitmap Image image = ImageCache.getInstance().getImage(id); Bitmap bitmap = image.getBitmap(); //判斷bitmap是否為空 if (bitmap == null) { // 判斷本地SDCard中是否有相關文件 if (Image.hasFile(id)) { InputStream is; try { is = new FileInputStream(Image.getFileFromSDCard(id)); bitmap = BitmapFactory.decodeStream(is); ImageCache.getInstance().cacheImage(new Image(id, bitmap)); continer.image.setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } } else { //本地也沒有,就從服務器下載 ImageDownload download = new ImageDownload(); download.loadDrawable(news.getImgUrl(), id + "", new FreedomCallback() { @Override public void imageLoaded(Bitmap imageDrawable, Object tag) { if (imageDrawable != null) { //構建adapter時傳入的回調接口,如果下載圖片成功,回調此方法 listCallback.imageLoaded(imageDrawable, id); } } }); continer.image.setImageResource(R.drawable.ic_launcher); } } else { //如果軟引用還存在,則直接拿來用 continer.image.setImageBitmap(bitmap); }

2、ListView 的初始化

關鍵在於回呼時能透過 tag 找回對應的 ImageView,避免圖片「錯位」。

 adapter = new NewsAdapter(context, new ListCallback() { @Override public void imageLoaded(Bitmap bitmap, Object tag) { //根據回調傳回的tag找到對應的ImageView ImageView imageView = (ImageView) listView.findViewWithTag(tag); if (imageView != null) { imageView.setImageBitmap(bitmap); } } }); listView = new ListView(context); listView.setAdapter(adapter);

四、圖片壓縮

上面的流程其實還有優化空間。我們預設下載回來的圖片尺寸已經合適,但實務上圖片往往偏大,這時就需要壓縮。常見做法有兩種:品質壓縮與寬高(取樣)壓縮。以下工具類別提供了一個不錯的起點。

 //圖片質量壓縮 public static Bitmap compressImage(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 質量壓縮方法,這裡100表示不壓縮,把壓縮後的數據存放到baos中 int options = 100; while (baos.toByteArray().length / 1024 > 100) { // 循環判斷如果壓縮後圖片是否大於100kb,大於繼續壓縮 baos.reset();// 重置baos即清空baos image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 這裡壓縮options%,把壓縮後的數據存放到baos中 options -= 10;// 每次都減少10 } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把壓縮後的數據baos存放到ByteArrayInputStream中 Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream數據生成圖片 return bitmap; } //圖片寬高壓縮 public static Bitmap getimage(String srcPath) { BitmapFactory.Options newOpts = new BitmapFactory.Options(); // 開始讀入圖片,此時把options.inJustDecodeBounds 設回true了 newOpts.inJustDecodeBounds = true; Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此時返回bm為空 newOpts.inJustDecodeBounds = false; int w = newOpts.outWidth; int h = newOpts.outHeight; // 這個設置圖片的寬高,根據實際需要設定 float hh = 800f;// 這裡設置高度為800f float ww = 480f;// 這裡設置寬度為480f // 縮放比。由於是固定比例縮放,只用高或者寬其中一個數據進行計算即可 int be = 1;// be=1表示不縮放 if (w > h && w > ww) {// 如果寬度大的話根據寬度固定大小縮放 be = (int) (newOpts.outWidth / ww); } else if (w < h && h > hh) {// 如果高度高的話根據寬度固定大小縮放 be = (int) (newOpts.outHeight / hh); } if (be <= 0) be = 1; newOpts.inSampleSize = be;// 設置縮放比例 // 重新讀入圖片,注意此時已經把options.inJustDecodeBounds 設回false了 bitmap = BitmapFactory.decodeFile(srcPath, newOpts); return compressImage(bitmap);// 壓縮好比例大小後再進行質量壓縮 }

此外,也可以把壓縮交給系統自動運算,在避免 OOM 的前提下盡量保留顯示品質:

 File file = Image.getFileFromSDCard(name, "pure"); Options opts = new Options(); opts.inJustDecodeBounds = true; BitmapFactory.decodeFile(file.getAbsolutePath(), opts); opts.inJustDecodeBounds = false; // 根據設定的值讓系統自動壓縮,這行代碼的參數是第一個是BitmapFactory.Options,第二個參數是調整後圖片最小的寬或者高,第三個參數是調整後圖片的內存占用量上限。 opts.inSampleSize = Util.computeSampleSize(opts, 600,(int) (1 * 1024 * 1024)); opts.inDither = false; opts.inPreferredConfig = Bitmap.Config.ARGB_8888; bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), opts);

一般來說,壓縮步驟安排在圖皮下載完成之後執行。至此,從下載、快取到顯示的完整鏈路就走通了。當然,這只是其中一種實作思路,非同步載入圖片仍有其他玩法。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved