1. 程式人生 > >Android學習筆記9-呼叫攝像頭和相簿

Android學習筆記9-呼叫攝像頭和相簿

呼叫攝像頭和手機的相簿

呼叫手機的攝像頭和相機拍照的功能,在許多app中都非常常見,當我們用qq,微信,微博等app給別人分享圖片時都會用到這個功能。


1,呼叫攝像頭拍照

activity_main.xml佈局程式碼

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width
="match_parent" android:orientation="vertical" >
<Button android:id="@+id/take_photo" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="take photo" /> <ImageView android:id="@+id/picture" android:
layout_width
="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" />
</LinearLayout>
  • 設定一個button用來點選進行開啟攝像頭進行拍照。
  • 設定一個imageView用來顯示拍到的圖片。

MainActivity.java程式碼

package com.example.chen.cameraalbumtest;

import android.
Manifest; import android.annotation.TargetApi; import android.content.ContentUris; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Build; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.content.FileProvider; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; public class MainActivity extends AppCompatActivity { public static final int TAKE_PHOTO = 1; private ImageView picture; private Uri imageUri; public static final int CHOOSE_PHOTO = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button takePhoto = (Button) findViewById(R.id.take_photo); Button chooseAlbum = (Button)findViewById(R.id.choose_from_album); picture = (ImageView) findViewById(R.id.picture); takePhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //建立File物件,用於儲存拍照後的照片 File outputImage = new File(getExternalCacheDir(),"output_image.jpg"); try { if (outputImage.exists()) { outputImage.delete(); } outputImage.createNewFile(); } catch (IOException e) { e.printStackTrace(); } if(Build.VERSION.SDK_INT >= 24) { imageUri = FileProvider.getUriForFile(MainActivity.this, "com.example.chen.cameraalbumtest.fileprovider" ,outputImage ); } else { imageUri = Uri.fromFile(outputImage); } //啟動相機 Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri ); startActivityForResult(intent,TAKE_PHOTO ); } }); } @Override protected void onActivityResult(int requestCode,int resultCode,Intent data) { switch (requestCode) { case TAKE_PHOTO: if(resultCode == RESULT_OK) { try { //將拍攝的照片顯示出來 Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver(). openInputStream(imageUri)); picture.setImageBitmap(bitmap); } catch(FileNotFoundException e ) { e.printStackTrace(); } } break; default: break; } } }

這裡我們詳細介紹一下button點選時間的邏輯:
首先,我們建立了一個File物件,用來儲存拍攝的照片,把圖片命名為 output_image.jpg,並將它放在手機SD卡的應用關聯快取目錄應用關聯快取目錄 是 sd卡專門用於存放當前應用快取資料的位置,呼叫getExternalCacheDir()就可以得到這個目錄。,具體在手機中的路徑是 /sdcard/Android/data/包名/cache。 之所以是使用應用關聯快取目錄是因為在Android 6.0時 讀寫SD卡被列入危險許可權,如果將圖片存放在sd卡其他目錄,需要執行時許可權。

接著,會對File物件進行處理,如果手機Android版本低於7.0,就呼叫 Uri的fromFile() 方法將File物件轉為Uri物件。這個Uri物件標識著這張圖片的本地真實路徑。如果高於7.0,就會呼叫 FileProvider的getUriForFile() 方法,將File物件轉換成一個包裝過的Uri物件
getUriForFile()包含三個引數

  • Context物件
  • 任意唯一的字串
  • 剛剛建立的File物件
    之所以需要這樣的轉換,是因為從Android 7.0 開始,直接使用本地真實路徑的Uri被認為是不安全的,會丟擲一個FileUriExposedException異常,FileProvider是一種特殊的內容提供器,它提供了類似內容提供器的機制對資料進行保護,可以選擇性的將封裝後的Uri分享給外部,提高應用的安全性。

再 **OnActivityResult()**函式中,如拍照成功,會呼叫BitmapFactory的decodeStream()方法將output_image.jpg 這張照片解析成Bitmap物件。再設定到imageView中顯示出來。

在Manifest.xml中對provider進行註冊

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.chen.cameraalbumtest">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
      
      <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.example.chen.cameraalbumtest.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"/>
        </provider>
    </application>

</manifest>

在provider中,Android:name是固定的,android:authorities必須和getUriForFile()中的第二個引數相同。

imageUri = FileProvider.getUriForFile(
MainActivity.this,"com.example.chen.cameraalbumtest.fileprovider" ,outputImage );

另外,還要再meta-data標籤中,指定Uri的共享路徑,並引用@xml/file_paths資源,現在需要我們建立

xml檔案中的external-path 就是用來指定Uri共享,name可以自己定義,path設定空置就表示整個sd卡進行共享。
在Android 4.4系統之前需要在AndroidManifest.xml中宣告訪問sd卡的許可權

之後,我們就可以執行程式


2,從相簿中選擇照片

添加布局

    <Button
        android:id="@+id/choose_from_album"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Choose from albunm"
        />

MainActivity.java檔案

package com.example.chen.cameraalbumtest;

import ...

public class MainActivity extends AppCompatActivity {

    public static final int TAKE_PHOTO = 1;
    private ImageView picture;
    private Uri imageUri;
    public static final int CHOOSE_PHOTO = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button takePhoto = (Button) findViewById(R.id.take_photo);
        Button chooseAlbum = (Button)findViewById(R.id.choose_from_album);
        picture = (ImageView) findViewById(R.id.picture);


        //設定點選事件 開啟相簿
        chooseAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(MainActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.
                        PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },1 );
                } else {
                    openAlbum();
                }
            }
        });
	/**
     * 開啟相簿
     */
    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,CHOOSE_PHOTO );
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,String[] permissions,
                                          int[] grantResults) {
        switch (requestCode) {
            case 1:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum();
                } else {
                    Toast.makeText(this, "你沒有許可權", Toast.LENGTH_SHORT).show();
                }
                break;
            default:break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode,int resultCode,Intent data) {
        switch (requestCode) {
            case TAKE_PHOTO:
                if(resultCode == RESULT_OK) {
                    try {
                        //將拍攝的照片顯示出來
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().
                                openInputStream(imageUri));
                        picture.setImageBitmap(bitmap);
                    } catch(FileNotFoundException e ) {
                        e.printStackTrace();
                    }
                }
                break;
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    //判斷手機的系統版本號
                    if (Build.VERSION.SDK_INT >= 19) {
                        //4.4系統的及以上用此方法處理照片
                        handleImageOnKitkat(data);
                    } else {
                        // 4.4一下的使用這個方法處理照片
                        handleImageBeforeKitkat(data);
                    }
                }
                break;
            default:
                break;
        }
    }

    @TargetApi(19)
    private void handleImageOnKitkat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            //如果是document型別的uri,則通過document id 處理
            String docId = DocumentsContract.getDocumentId(uri);
            if("com.android.providers.media.documents".equals(uri.getAuthority())) {
                //解析出數字格式的id
                String id  = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID+ "=" +id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection );
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse
                        ("content://downloads/public_downloads"),Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            //如果是content型別的uri,則用普通方式處理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            //如果是file型別的uri,直接獲取圖片路徑
            imagePath = uri.getPath();
        }
        displayImage(imagePath);
    }

    private void handleImageBeforeKitkat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    private String getImagePath(Uri uri,String selection) {
        String path = null;
        //通過uri 和 selection 獲取真實的圖片路徑
        Cursor cursor = getContentResolver().query(uri,null,selection,null,null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images
                        .Media.DATA));

            }
            cursor.close();
        }
        return path;
    }

    /**
     * 根據圖片的路徑顯示圖片
     */
    private  void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            picture.setImageBitmap(bitmap);
        } else {
            Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
        }
    }


}

注意,我們在點選事件中添加了申請執行時許可權,WRITE_EXTERNAL_STORAGE這個危險許可權,因為相簿是儲存在手機中的SD卡的,這個許可權能夠賦予我們對SD卡 讀和寫的能力。
當用戶同意授權後,會呼叫openAlbum()方法,用來開啟相簿,指定intent的action為 ** android.intent.action.GET_CONTENT**,
再用startActivityForResult() 方法啟動intent. 在 onActivityResult() 方法中,我們要對得到的圖片進行處理 如果是4.4以上的系統會呼叫handleImageOnKitKat() 方法,4.4以下的系統會呼叫 handleImageBeforeKitKat() 方法。

現在我們執行程式…


選擇圖片