android 擷取本地圖片(二)

來源:互聯網
上載者:User

android 擷取本地圖片(二)

連結上一篇博文

本篇博文接著講述本地圖片的擷取。
下面給出擷取本地圖片的非同步線程類LoadLoacalPhotoCursorTask的代碼:

/*** 擷取本地圖片的非同步線程類*/public class LoadLoacalPhotoCursorTask extends AsyncTask {    private Context mContext;    private final ContentResolver mContentResolver;    private boolean mExitTasksEarly = false;//退出任務線程的標誌位    private OnLoadPhotoCursor onLoadPhotoCursor;//定義回調介面,擷取解析到的資料    private ArrayList uriArray = new ArrayList();//存放圖片URI    private ArrayList origIdArray = new ArrayList();//存放圖片ID    public LoadLoacalPhotoCursorTask(Context mContext) {        this.mContext = mContext;        mContentResolver = mContext.getContentResolver();    }    @Override    protected Object doInBackground(Object... params) {        String[] projection = {                MediaStore.Images.Media._ID        };        Uri ext_uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;        String where = MediaStore.Images.Media.SIZE + >=?;        /**        * 這個查詢操作完成圖片大小大於100K的圖片的ID查詢。        * 大家可能疑惑為什麼不查詢得到圖片DATA呢?        * 這樣是為了節省記憶體。通過圖片的ID可以查詢得到指定的圖片        * 如果這裡就把圖片資料查詢得到,手機中的圖片大量的情況下        * 記憶體消耗嚴重。那麼,什麼時候查詢圖片呢?應該是在Adapter        * 中完成指定的ID的圖片的查詢,並不一次性載入全部圖片資料        */        Cursor c = MediaStore.Images.Media.query(                mContentResolver,                ext_uri,                projection,                where,                new String[]{1 * 100 * 1024 + },                MediaStore.Images.Media.DATE_ADDED+ desc);        int columnIndex = c.getColumnIndexOrThrow(MediaStore.Images.Media._ID);        int i = 0;        while (c.moveToNext() && i < c.getCount() && !mExitTasksEarly) {   //移到指定的位置,遍曆資料庫            long origId = c.getLong(columnIndex);            uriArray.add(                    Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,                            origId + )            );            origIdArray.add(origId);            c.moveToPosition(i);            i++;        }        c.close();//關閉資料庫        if (mExitTasksEarly) {            uriArray = new ArrayList();            origIdArray = new ArrayList();        }        return null;    }    @Override    protected void onPostExecute(Object o) {        if (onLoadPhotoCursor != null && !mExitTasksEarly) {        /**        * 查詢完成之後,設定回調介面中的資料,把資料傳遞到Activity中        */          onLoadPhotoCursor.onLoadPhotoSursorResult(uriArray, origIdArray);        }    }    @Override    protected void onCancelled() {        super.onCancelled();    //To change body of overridden methods use File | Settings | File Templates.        mExitTasksEarly = true;    }    public void setExitTasksEarly(boolean exitTasksEarly) {        this.mExitTasksEarly = exitTasksEarly;    }    public void setOnLoadPhotoCursor(OnLoadPhotoCursor onLoadPhotoCursor) {        this.onLoadPhotoCursor = onLoadPhotoCursor;    }    public interface OnLoadPhotoCursor {        public void onLoadPhotoSursorResult(ArrayList uriArray, ArrayList origIdArray);    }}

下面給出載入圖片的類ImageWorker的代碼:

/** * 手機本地圖片非同步載入處理類 * 圖片的載入效能影響很大,使用弱引用和軟引用 * 緩衝圖片,加快響應的速度,提高效能。 */public class ImageWorker {    //這個值設定的是載入圖片的動畫效果的間隔時間,達到漸隱漸顯的效果    private static final int FADE_IN_TIME = 200;    private boolean mExitTasksEarly = false;//判斷圖片載入任務是否提前退出    private boolean mPauseWork = false;//載入圖片線程是否掛起    private final Object mPauseWorkLock = new Object();//鎖對象,這個鎖對象是為了判斷是否進行圖片的載入    protected final Resources mResources;    private final ContentResolver mContentResolver;//內容解析者    private final BitmapFactory.Options mOptions;    private final HashMap> bitmapCache = new HashMap>();//用於緩衝圖片,每一個緩衝的圖片對應一個Long類型的id值,SoftReference對應該圖片的軟引用    private Bitmap mLoadBitmap;//GridView中預設的背景圖片    //構造器    public ImageWorker(Context context) {        this.mResources = context.getResources();        this.mContentResolver = context.getContentResolver();        mOptions = new BitmapFactory.Options();        mOptions.inSampleSize = 3;//縮放圖片為原來的1/9。一般應用中載入圖片都會進行圖片的縮放,防止記憶體溢出的問題。這部分的內容有關Bitmap,請參考我的博文(http://blog.csdn.net/u010156024/article/details/44103557)    }    /**     * 載入圖片     * @param origId 每個本地圖片對應一個id值     * @param imageView     */    public void loadImage(long origId, ImageView imageView) {        BitmapDrawable bitmapDrawable = null;        //先從緩衝中載入圖片,如果緩衝中有,載入圖片即可。        //如果緩衝中沒有,首先判斷當前任務是否暫停,沒有暫停則使用loadBitmapTask非同步任務線程載入圖片        if (bitmapCache.containsKey(origId)) {            bitmapDrawable = bitmapCache.get(origId).get();        }        if (bitmapDrawable != null) {            imageView.setImageDrawable(bitmapDrawable);        } else if (cancelPotentialWork(origId, imageView)) {            final LoadBitmapTask loadBitmapTask = new LoadBitmapTask(imageView);            final AsyncDrawable asyncDrawable =                    new AsyncDrawable(mResources, mLoadBitmap, loadBitmapTask);            imageView.setImageDrawable(asyncDrawable);            //SERIAL_EXECUTOR 啟動線程,保證線程順序依次執行            loadBitmapTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, origId);        }    }/*** 該類提供這個方法設定GridView中每個item預設的圖片*/    public void setLoadBitmap(Bitmap mLoadBitmap) {        this.mLoadBitmap = mLoadBitmap;    }    /**     * 設定圖片動畫  載入圖片漸隱漸顯的效果     *     * @param imageView     * @param drawable     */    private void setImageDrawable(ImageView imageView, Drawable drawable) {        final TransitionDrawable td =                new TransitionDrawable(new Drawable[]{                        new ColorDrawable(android.R.color.transparent),                        drawable                });        imageView.setImageDrawable(td);        td.startTransition(FADE_IN_TIME);    }    /**     * 取消可能在運行並且暫停任務。     *     * @param origId     * @param imageView     * @return     */    private static boolean cancelPotentialWork(long origId, ImageView imageView) {        final LoadBitmapTask loadBitmapTask = getBitmapWorkerTask(imageView);        if (loadBitmapTask != null) {            final long bitmapOrigId = loadBitmapTask.origId;            if (bitmapOrigId == origId) {                loadBitmapTask.cancel(true);            } else {                // The same work is already in progress.                return false;            }        }        return true;    }    /**     * 圖片非同步載入線程類-任務線程     */    private class LoadBitmapTask extends AsyncTask {        private long origId;        private WeakReference imageViewReference;//指向Imageview的弱引用,把圖片緩衝在HashMap> bitmapCache中。        public LoadBitmapTask(ImageView imageView) {            imageViewReference = new WeakReference(imageView);        }        @Override        protected BitmapDrawable doInBackground(Long... params) {            origId = params[0];            Bitmap bitmap = null;            BitmapDrawable drawable = null;            // Wait here if work is paused and the task is not cancelled            synchronized (mPauseWorkLock) {                while (mPauseWork && !isCancelled()) {                    try {                        mPauseWorkLock.wait();                    } catch (InterruptedException e) {                    }                }            }            if (bitmapCache != null && !isCancelled() && getAttachedImageView() != null                    && !mExitTasksEarly) {                //這裡是根據圖片的id值查詢手機本地的圖片,擷取圖片的縮圖,MICRO_KIND 代表96*96大小的圖片                bitmap = MediaStore.Images.Thumbnails.getThumbnail(                        mContentResolver,                        origId,                    MediaStore.Images.Thumbnails.MICRO_KIND,                        mOptions                );            }            if (bitmap != null) {                drawable = new BitmapDrawable(mResources, bitmap);                bitmapCache.put(origId,new SoftReference(drawable));            }            return drawable;        }        @Override        protected void onPostExecute(BitmapDrawable drawable) {            if (isCancelled() || mExitTasksEarly) {                drawable = null;            }            final ImageView imageView = getAttachedImageView();            if (drawable != null && imageView != null) {                setImageDrawable(imageView, drawable);            }        }       @Override        protected void onCancelled(BitmapDrawable drawable) {            super.onCancelled(drawable);            synchronized (mPauseWorkLock) {                mPauseWorkLock.notifyAll();            }        }        /**         * 返回與此任務相關的ImageView,         * 如果ImageView 內的任務是當前任務,         * 則返回當前ImageView,否則返回null。         * @return         */        private ImageView getAttachedImageView() {            final ImageView imageView = imageViewReference.get();            final LoadBitmapTask bitmapWorkerTask = getBitmapWorkerTask(imageView);            if (this == bitmapWorkerTask) {                return imageView;            }            return null;        }    }    /**     * 儲存非同步資訊圖片資源類     */    private static class AsyncDrawable extends BitmapDrawable {        private final WeakReference bitmapWorkerTaskReference;//虛引用        public AsyncDrawable(Resources res, Bitmap bitmap, LoadBitmapTask bitmapWorkerTask) {            super(res, bitmap);            bitmapWorkerTaskReference =                    new WeakReference(bitmapWorkerTask);        }        public LoadBitmapTask getLoadBitmapTask() {            return bitmapWorkerTaskReference.get();        }    }    /**     * 返回圖片資源記憶體放的非同步線程,如果存在,則返回,不存在,返回null。     *     * @param imageView 當前存放非同步資源圖片的ImageView     * @return     */    private static LoadBitmapTask getBitmapWorkerTask(ImageView imageView) {        if (imageView != null) {            final Drawable drawable = imageView.getDrawable();            if (drawable instanceof AsyncDrawable) {                final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;                return asyncDrawable.getLoadBitmapTask();            }        }        return null;    }    /**     * 設定非同步任務是否暫停,false為啟動,true為暫停。     * @param pauseWork     */    public void setPauseWork(boolean pauseWork) {        synchronized (mPauseWorkLock) {            mPauseWork = pauseWork;            if (!mPauseWork) {                mPauseWorkLock.notifyAll();            }        }    }    /**     * 退出線程     * @param exitTasksEarly     */    public void setExitTasksEarly(boolean exitTasksEarly) {        mExitTasksEarly = exitTasksEarly;        setPauseWork(false);//這個設定為false,使得退出任務優雅。這個設定為true也是可行的,也沒有問題,可以達到同樣的效果。但是可以比較設定為true或false的區別。    }}

至此 全部講述了android手機中擷取本地圖片的全部內容。這個項目代碼在Github中開放學習,非常值得大家深入研究學習之後。
總結:
整個項目使用到了ContentResolver、軟引用、弱引用、緩衝、非同步線程、節省記憶體技巧-滾動不載入、鎖機制、圖片縮放、線程通訊、動畫等非常實用的方法、技巧。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.