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

依指定路徑掃描圖片檔案:目錄遍歷、格式過濾與 Bitmap 縮放

編輯:Android 開發教學

需求

給定一個資料夾路徑,列出裡面所有圖片檔案(png、gif、jpg、jpeg)的相關資訊:檔名、大小、建立時間與絕對路徑,並在列表中顯示縮圖。

工具類:檔案大小格式化、路徑掃描、格式驗證、縮圖解碼

public class Util {

    /** 計算檔案大小,自動換算成 B / KB / MB */
    public static String ShowLongFileSzie(Long length) {
        if (length >= 1048576) {
            return (length / 1048576) + "MB";
        } else if (length >= 1024) {
            return (length / 1024) + "KB";
        } else if (length < 1024) {
            return length + "B";
        } else {
            return "0KB";
        }
    }

    /** 取得指定路徑下的全部圖片資訊 */
    public static List<AddFileInfo> getSDPathFrom() {
        List<AddFileInfo> imagePathList = new ArrayList<AddFileInfo>();

        // 目標資料夾路徑
        String filePath = Environment.getExternalStorageDirectory().toString()
                + File.separator + "BigNoxHD/cache/";

        File fileAll = new File(filePath);
        File[] files = fileAll.listFiles();

        // 逐一檢查並過濾出圖片格式
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (checkIsFile(file.getPath())) {
                String time = new SimpleDateFormat("yyyy-MM-dd")
                        .format(new Date(file.lastModified()));
                AddFileInfo info = new AddFileInfo(file.getName(),
                        Util.ShowLongFileSzie(file.length()), time, file.getAbsolutePath());
                imagePathList.add(info);
            }
        }
        return imagePathList;
    }

    /** 驗證副檔名是否為圖片 */
    public static boolean checkIsFile(String fName) {
        boolean isImageFile = false;
        String FileEnd = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();
        if (FileEnd.equals("jpg") || FileEnd.equals("png")
                || FileEnd.equals("gif") || FileEnd.equals("jpeg")) {
            isImageFile = true;
        }
        return isImageFile;
    }

    /**
     * 依路徑載入並縮放圖片,避免大圖直接進記憶體造成 OOM
     * @param path 檔案路徑
     * @param w 目標寬
     * @param h 目標高
     */
    public static Bitmap convertToBitmap(String path, int w, int h) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        // 第一次只讀取尺寸,不真正配置像素記憶體
        opts.inJustDecodeBounds = true;
        opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
        BitmapFactory.decodeFile(path, opts);

        int width = opts.outWidth;
        int height = opts.outHeight;
        float scaleWidth = 0.f, scaleHeight = 0.f;
        if (width > w || height > h) {
            scaleWidth = ((float) width) / w;
            scaleHeight = ((float) height) / h;
        }

        opts.inJustDecodeBounds = false;
        float scale = Math.max(scaleWidth, scaleHeight);
        opts.inSampleSize = (int) scale;

        WeakReference<Bitmap> weak = new WeakReference<Bitmap>(BitmapFactory.decodeFile(path, opts));
        return Bitmap.createScaledBitmap(weak.get(), w, h, true);
    }
}

這裡有個關鍵技巧值得單獨說明:inJustDecodeBounds = true 時,decodeFile 只讀取圖片的寬高而不配置像素記憶體。先用它量出原圖尺寸、算出 inSampleSize,再正式解碼,就能大幅降低大圖造成 OOM 的風險。

MainActivity:用 ListView 呈現

public class MainActivity extends Activity {

    private ListView mListview;
    private List<AddFileInfo> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        mListview = (ListView) findViewById(R.id.listview);
        list = Util.getSDPathFrom();
        mListview.setAdapter(new Adapter(MainActivity.this));
    }

    class Adapter extends BaseAdapter {
        private LayoutInflater inflater;
        private Context context;

        public Adapter(Context context) {
            this.context = context;
            this.inflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (null == convertView) {
                convertView = inflater.inflate(R.layout.item_mytask_file_listview, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            AddFileInfo info = (AddFileInfo) getItem(position);
            holder.img.setImageBitmap(Util.convertToBitmap(info.getPath(), 99, 99));
            holder.tv_name.setText("文件名稱:" + info.getName());
            holder.size.setText("文件大小:" + info.getSize());
            holder.time.setText("文件創建時間:" + info.getTime());
            return convertView;
        }
    }

    class ViewHolder {
        private TextView tv_name;
        private TextView size;
        private TextView time;
        private ImageView img;

        public ViewHolder(View view) {
            img = (ImageView) view.findViewById(R.id.img);
            tv_name = (TextView) view.findViewById(R.id.item_file_name);
            size = (TextView) view.findViewById(R.id.item_file_size);
            time = (TextView) view.findViewById(R.id.item_file_time);
        }
    }
}

Adapter 裡用的是標準的 ViewHolder 模式:convertView 為 null 時才 inflate 並把 holder 掛上 tag,複用時直接取回,避免每捲動一次就重複 findViewById。

別忘了加權限

<!-- SD卡權限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

在 Android 6.0 以上,WRITE_EXTERNAL_STORAGE 還必須另外向使用者動態申請,否則讀不到路徑下的檔案。

源碼下載

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