1. 程式人生 > >Android 如何從系統圖庫中選擇圖片

Android 如何從系統圖庫中選擇圖片

這幾天我都在做Android的App,同時學習它的API,我將分享一些我學到的東西,比如: 如何從系統圖庫中選擇圖片。

首先,讓我們來看看如何將手機系統圖庫整合到你的App中,然後再從相簿中選擇圖片來做一些事。例如,在Facebook的App,你就可以直接選擇手機上的圖片上傳到你的個人資料。

讓我們來做一個簡單例子,要求:

  1. 螢幕上顯示一個按鈕和圖片檢視控制元件。
  2. 點選“載入圖片”按鈕,將使用者重定向到Android的圖片庫,在那裡可以選擇一個圖片。
  3. 一旦圖片被選中,圖片將在主螢幕上的圖片檢視控制元件中顯示。

讓我們開始。

步驟1:建立基本的Android專案

在Eclipse中,點選New > Project > Android Project

,給專案取名為“ImageGalleryDemo”,然後選擇Android2.1或sdk 7。

一旦這一步完成,你將看到一個基本的hello world程式。

步驟2:修改佈局檔案

在我們的例子中,我們需要一個簡單的佈局:一個ImageView控制元件來顯示我們選中的圖片,一個Button控制元件點選重定向到手機相簿。

在專案中開啟layout/main.xml,然後替換成下面的程式碼:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://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_height="wrap_content"
        android:layout_weight="1"></ImageView>
    <Button
        android:id="@+id/buttonLoadPicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="Load Picture"
        android:layout_gravity="center"></Button>
</LinearLayout>

步驟3:編寫重定向到圖片庫的程式碼

現在我們需要寫一些Java程式碼來處理按鈕的點選事件,而重定向到圖片庫的程式碼如下:

Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
 
startActivityForResult(i, RESULT_LOAD_IMAGE);
注意:這裡要傳一個整形的常量RESULT_LOAD_IMAGEstartActivityForResult()方法。

步驟4:獲取選中的圖片

一旦使用者選擇了一張圖片,onActivityResult()方法將會被呼叫。我們需要處理這個方法得到的資料,程式碼如下:

@Override
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();

        // String picturePath contains the path of selected Image
}

注意:onActivityResult()方法只有當圖片被選中後才會呼叫。在這個方法中,我們需要檢查requestCode是否是我們之前傳給startActivityForResult()方法的RESULT_LOAD_IMAGE。

最終程式碼
ImageGalleryDemoActivity類的最終程式碼如下:

package net.viralpatel.android.imagegalleray;
 
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
 
public class ImageGalleryDemoActivity extends Activity {
 
    private static int RESULT_LOAD_IMAGE = 1;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
        buttonLoadImage.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View arg0) {
 
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
 
                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
    }
 
    @Override
    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));
 
        }
 
    }
}


程式截圖
第一屏:使用者將重定向到手機相簿

使用者從相簿選擇圖片

在我們的App顯示使用者選中的圖片