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

Android 從系統圖庫選取圖片並顯示的完整流程

編輯:關於 Android 程式設計

從圖庫挑一張圖顯示在自己的界面上,是很基礎也很常被問到的需求。實現起來其實不麻煩,三步就能搞定。

第一步:佈局中放一個 ImageView 和一個按鈕

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ImageView
        android:id="@+id/imgView"
        android:layout_width="fill_parent"
        android:layout_weight="1"
        android:layout_height="wrap_content">
    </ImageView>

    <Button
        android:layout_height="wrap_content"
        android:text="Load Picture"
        android:layout_width="wrap_content"
        android:id="@+id/buttonLoadPicture"
        android:layout_weight="0"
        android:layout_gravity="center">
    </Button>
</LinearLayout>

第二步:用 Intent 喚起圖庫

本質上就是一個隱式 Intent:

Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);

第三步:在 onActivityResult 中取回並顯示

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        ImageView imageView = (ImageView) findViewById(R.id.imgView);
        imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
    }
}

關鍵是這一句:Uri selectedImage = data.getData(); 它拿到了用戶選中圖片的 Uri。後續通過 ContentResolver 查詢 MediaStore,從 DATA 列取出真實路徑,再交給 BitmapFactory 解碼顯示。

實務上要注意兩點:一是 Android 6.0 以上讀取外部媒體需要 READ_EXTERNAL_STORAGE 運行時權限;二是大圖直接 decodeFile 容易 OOM,建議按 inSampleSize 降採樣,或者改用 Glide、Coil 這類圖片庫加載。

感謝閱讀,希望能幫助到大家。

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