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

Android 多媒體:調用攝像頭拍照與從相冊選圖

編輯:關於 Android 程式設計

概述

這個示例實現三件事:調用系統相機拍照、對照片做壓縮、從本地相冊中挑選圖片。由於要讀取相冊內容,需要申請讀取外部存儲的權限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

示例代碼

public class MainActivity extends Activity implements View.OnClickListener {

    private Button mButtonTakePhoto;
    private Button mButtonGetPhoto;
    private ImageView mImageViewPhoto;
    private File mFile;   // 存儲圖片的文件

    public static final int GET_PIC_FROM_CAMERA  = 0x123;
    public static final int GET_PIC_FROM_GALLERY = 0x124;

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

        mButtonTakePhoto = (Button) findViewById(R.id.button_take_photo);
        mButtonGetPhoto = (Button) findViewById(R.id.button_get_photo);
        mImageViewPhoto = (ImageView) findViewById(R.id.imageView_camera);

        mButtonTakePhoto.setOnClickListener(this);
        mButtonGetPhoto.setOnClickListener(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case GET_PIC_FROM_CAMERA:
                if (resultCode == RESULT_OK) {
                    ImageZip.zipImage(mFile.getAbsolutePath());   // 壓縮圖片
                    mImageViewPhoto.setImageURI(Uri.fromFile(mFile));
                }
                break;

            case GET_PIC_FROM_GALLERY:
                if (resultCode == RESULT_OK) {
                    getImageFromGallery(data);
                }
                break;
        }
    }

    /** 從本地相冊中選擇並取得相片 */
    private void getImageFromGallery(Intent 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();   // 用完及時關閉,避免資源洩漏

        // 相冊原圖往往過大,不能直接展示,先壓縮
        ImageZip.zipImage(picturePath);
        mImageViewPhoto.setImageBitmap(BitmapFactory.decodeFile(picturePath));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_take_photo:
                getPictureFromCamera();
                break;

            case R.id.button_get_photo:
                // 左起參數:選擇行為,以及系統相冊的 URI
                Intent i = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, GET_PIC_FROM_GALLERY);
                break;
        }
    }

    /** 向 onActivityResult 發起請求,取得拍攝生成的圖片 */
    private void getPictureFromCamera() {
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);

        // 確定存儲拍照結果的文件路徑
        mFile = new File(Environment.getExternalStorageDirectory(),
                System.currentTimeMillis() + ".jpg");
        try {
            mFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
        startActivityForResult(intent, GET_PIC_FROM_CAMERA);
    }
}

圖片壓縮工具類

public class ImageZip {

    /** 壓縮圖片並原地覆蓋 */
    public static void zipImage(String savePath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;          // 只讀取邊界信息,不真正加載像素
        BitmapFactory.decodeFile(savePath, options);

        options.inSampleSize = computeInitialSampleSize(options, 480, 480 * 960);
        options.inJustDecodeBounds = false;

        Bitmap bitmap = BitmapFactory.decodeFile(savePath, options);
        try {
            FileOutputStream fos = new FileOutputStream(savePath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        bitmap.recycle();
        bitmap = null;
        System.gc();
    }

    /** 只解壓縮後的 Bitmap,不落盤 */
    public static Bitmap getZipImage(String savePath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(savePath, options);

        options.inSampleSize = computeInitialSampleSize(options, 480, 480 * 960);
        options.inJustDecodeBounds = false;

        Bitmap bitmap = BitmapFactory.decodeFile(savePath, options);
        bitmap.recycle();
        bitmap = null;
        System.gc();
        return bitmap;
    }

    public int computeSampleSize(BitmapFactory.Options options,
                                 int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
        int roundedSize;
        if (initialSize <= 8) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }
        return roundedSize;
    }

    public static int computeInitialSampleSize(BitmapFactory.Options options,
                                               int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;

        int lowerBound = (maxNumOfPixels == -1) ? 1
                : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == -1) ? 128
                : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));

        if (upperBound < lowerBound) {
            return lowerBound;
        }
        if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }
}

佈局文件

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/button_take_photo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Take Photo" />

        <Button
            android:id="@+id/button_get_photo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Get from Gallery" />
    </LinearLayout>

    <ImageView
        android:id="@+id/imageView_camera"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

要點回顧:相冊選圖用 Intent.ACTION_PICK 搭配 EXTERNAL_CONTENT_URI,返回後通過 ContentResolver 查詢 MediaStore.Images.Media.DATA 拿到真實路徑;壓縮的核心技巧是兩次解碼——第一次設 inJustDecodeBounds = true 只取尺寸信息,算出合適的 inSampleSize 後再真正加載像素,這樣能在不解出大位圖的前提下完成降採樣,有效規避 OOM。

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