Android呼叫系統相簿和相機拍照

淡然行走發表於2017-12-07

打算把最近專案中用到的知識點記錄下來,順便加深下記憶。相信很多軟體都有這樣的需求,需要呼叫手機的相簿來選取圖片,或者呼叫相機拍照。廢話不多說,直接上程式碼。
一.呼叫系統相簿
1.首先需要先新增許可權:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
當然在android6.0之後,我們還需要在程式碼中動態新增許可權,詢問使用者是否同意授權,這個在後面說。

2.呼叫相簿並返回選擇的圖片

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

3.重寫onActivityResult

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 0 && resultCode == Activity.RESULT_OK && data != null){
            Uri uri = data.getData();
            String[] filePathColumns = {MediaStore.Images.Media.DATA};
            Cursor c = getContentResolver().query(uri, filePathColumns, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePathColumns[0]);
            String imagePath = c.getString(columnIndex);
            Bitmap bm = BitmapFactory.decodeFile(imagePath);
            img.setImageBitmap(bm);
            c.close();
        }
    }

4.動態獲取許可權
在6.0之後,我們必須要在程式碼中動態的獲取許可權

if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED )
        {
            //許可權還沒有授予,需要在這裡寫申請許可權的程式碼
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    GET_PERMISSION_REQUEST);
        }else {
            //許可權已授予,執行

        }

二.呼叫相機拍照並返回圖片
1.新增許可權

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

2.呼叫相機拍照

  Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //系統常量, 啟動相機的關鍵
  startActivityForResult(intent, 1); // 引數常量為自定義的request code, 在取返回結果時有用

3.重寫onActivityResult

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 1 && resultCode == RESULT_OK && data != null){
            String sdState= Environment.getExternalStorageState();
            if(!sdState.equals(Environment.MEDIA_MOUNTED)){
                return;
            }
            new android.text.format.DateFormat();
            String name= android.text.format.DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))+".jpg";
            Bundle bundle = data.getExtras();
            //獲取相機返回的資料,並轉換為圖片格式
            Bitmap bitmap = (Bitmap)bundle.get("data");
            FileOutputStream fout = null;
            File file = new File("/sdcard/pintu/");
            file.mkdirs();
            String filename=file.getPath()+name;
            try {
                fout = new FileOutputStream(filename);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);//影象壓縮
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }finally{
                if(fout!=null){
                    try {
                        fout.flush();
                        fout.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            //插入圖片
            img.setImageBitmap(bitmap);

        }
    }

4.動態新增許可權

 if(ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA)!=PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA},
                    GET_PERMISSION_REQUEST);
        }else {

        }

下面是全部程式碼:
main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android" >
    <Button
        android:id="@+id/btn_photo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="呼叫相簿"/>
    <Button
        android:id="@+id/btn_camera"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="呼叫相機"/>
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/img"/>
    </LinearLayout>

AndroidManifest.xml

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

    <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>
    </application>
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

</manifest>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private Button mPhoto;
    private ImageView img;
    private Button mCamera;
    private final int GET_PERMISSION_REQUEST = 100; //許可權申請自定義碼

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mCamera = (Button) findViewById(R.id.btn_camera);
        mPhoto = (Button) findViewById(R.id.btn_photo);
        img = (ImageView) findViewById(R.id.img);
        mPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               getPhoto();
            }
        });
        mCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getCamera();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 0 && resultCode == Activity.RESULT_OK && data != null){
            Uri uri = data.getData();
            String[] filePathColumns = {MediaStore.Images.Media.DATA};
            Cursor c = getContentResolver().query(uri, filePathColumns, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePathColumns[0]);
            String imagePath = c.getString(columnIndex);
            Bitmap bm = BitmapFactory.decodeFile(imagePath);
            img.setImageBitmap(bm);
            c.close();
        }else if(requestCode == 1 && resultCode == RESULT_OK && data != null){
            String sdState= Environment.getExternalStorageState();
            if(!sdState.equals(Environment.MEDIA_MOUNTED)){
                return;
            }
            new android.text.format.DateFormat();
            String name= android.text.format.DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))+".jpg";
            Bundle bundle = data.getExtras();
            //獲取相機返回的資料,並轉換為圖片格式
            Bitmap bitmap = (Bitmap)bundle.get("data");
            FileOutputStream fout = null;
            File file = new File("/sdcard/pintu/");
            file.mkdirs();
            String filename=file.getPath()+name;
            try {
                fout = new FileOutputStream(filename);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);//影象壓縮
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }finally{
                if(fout!=null){
                    try {
                        fout.flush();
                        fout.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            //插入圖片
            img.setImageBitmap(bitmap);

        }
    }
    //呼叫相簿許可權
    private void getPhoto(){
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED )
        {
            //許可權還沒有授予,需要在這裡寫申請許可權的程式碼
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    GET_PERMISSION_REQUEST);
        }else {
            //許可權已授予,執行
            Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent,0);
        }
    }
    //呼叫相機許可權
    private void getCamera(){
        if(ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA)!=PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA},
                    GET_PERMISSION_REQUEST);
        }else {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //系統常量, 啟動相機的關鍵
            startActivityForResult(intent, 1); // 引數常量為自定義的request code, 在取返回結果時有用
        }
    }

}

相關文章