溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

android中怎么實現在相冊中選擇圖片

發布時間:2021-06-26 17:08:50 來源:億速云 閱讀:134 作者:Leah 欄目:移動開發

這期內容當中小編將會給大家帶來有關android中怎么實現在相冊中選擇圖片,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

首先在 activity_main.xml 文件中增加一個 Button,用來觸發從相冊中選擇圖片的功能。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context="com.cofox.mycameraalbum.MainActivity">

  <Button
    android:id="@+id/button_take_photo"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAllCaps="false"
    android:text="Tack Photo"/>
  <Button
    android:id="@+id/button_choose_from_album"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAllCaps="false"
    android:text="Choose From Album"/>
  <ImageView
    android:id="@+id/photo_pictrue"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"/>

</LinearLayout>

這段代碼中的 android:id="@+id/button_choose_from_album" 按鈕就是我們的主角了。

然后要在MainActivity.java中,加入從相冊選圖片的邏輯。

聲明 Button 按鈕

復制代碼 代碼如下:


Button btnChooseFromAlbum = (Button)findViewById(R.id.button_choose_from_album);//相冊選擇圖片按鈕

添加按鈕的點擊事件

//打開相冊選擇圖片
    btnChooseFromAlbum.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();
        }
      }
    });

這段代碼中,先要判斷 PackageManager.PERMISSION_GRANTED 權限的情況,如果沒有權限就需要添加,有的話直接 openAlbum(); 打開相冊。

ActivityCompat.requestPermissions 執行獲取權限的操作,然后由用戶選擇是否給予權限,根據用戶的選擇,系統來決定是否可以繼續執行 openAlbum()功能。這個就需要用到 onRequestPermissionsResult 了。代碼的邏輯是,如果給了權限就執行 openAlbum(),如果不給權限就返回給用戶沒有此權限的提示即可。("You denied the permision.")

@Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode){
      case 1:
        if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
          openAlbum();
        }else{
          Toast.makeText(this, "You denied the permision.", Toast.LENGTH_LONG).show();
        }
        break;
      default:
    }
  }

openAlbum() 就是打開相冊,代碼邏輯很清晰吧?但是,還沒完呢。因為如何打開還需要一些邏輯。先看 openAlbum() 的代碼。

private void openAlbum() {
    Intent intent = new Intent("android.intent.action.GET_CONTENT");
    intent.setType("image/*");
    startActivityForResult(intent, CHOOSE_PHOTO);//打開相冊
  }

這里的 Intent 是給相冊準備的,然后調用 startActivityForResult() 才打開相冊。這時出現的 CHOOSE_PHOTO 是給 onActivityResult 中判斷走那個分支的條件參數。我們應該在 MainActivity.java 中增加一個全局變量聲明

public static final int CHOOSE_PHOTO = 2;

在 onActivityResult 中增加switch case的 CHOOSE_PHOTO 分支。分之內根據不同的系統版本執行不同的代碼邏輯。因為 android 4.4 是一個文件訪問安全處理方式的分水嶺,4.4以下的系統使用直接文件地址,4.4 及以上系統使用不再返回真實的圖片地址了。所以,代碼的處理方法就有所不同。4.4及以上系統需要對相冊返回的圖片地址進行解析。這里確定分作兩個方法來分別處理 handleImageOnKitKat(data) 和 handeleImageBeforeKitKat(data)。

case CHOOSE_PHOTO:
        if(resultCode == RESULT_OK){
          //判斷手機系統版本號
          if(Build.VERSION.SDK_INT >= 19){
            //4.4及以上系統使用這個方法處理圖片
            handleImageOnKitKat(data);
          }else{
            //4.4以下系統使用這個方法處理圖片
            handeleImageBeforeKitKat(data);
          }
        }
        break;

在 handleImageOnKitKat(data) 中對地址進行解析,根據三種不同的提供Uri方式采用不同的方法。

document 類型的 Uri

content 類型的 uri

file 類型的 Uri

  @TargetApi(19)
  private void handleImageOnKitKat(Intent data) {
//    Toast.makeText(this,"到了handleImageOnKitKat(Intent data)方法了", Toast.LENGTH_LONG).show();
    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())){
        String id = docId.split(":")[1];//解析出數字格式的 id
        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);//顯示選中的圖片
  }

注意那個 @TargetApi(19) ,因為我們的項目最小兼容系統設置的是 15,而代碼中的 DocumentsContract.isDocumentUri 和 DocumentsContract.getDocumentId 有系統兼容性需要處理。

當我們通過各個途徑,已經獲取到圖片路徑的之后,自然就是顯示圖片了。于是最后一句代碼就是調用 displayImage 方法來實現圖片的顯示了。

對于 handeleImageBeforeKitKat 就要簡單的多了。直接取得地址顯示。

  private void handeleImageBeforeKitKat(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_LONG).show();
    }
  }

MainActivity.java完整代碼:

package com.cofox.mycameraalbum;

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.annotation.NonNull;
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;
  public static final int CHOOSE_PHOTO = 2;
  private ImageView picture;
  private Uri imageUri;

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

    Button btnTakePhoto = (Button) findViewById(R.id.button_take_photo);  //拍照按鈕
    Button btnChooseFromAlbum = (Button)findViewById(R.id.button_choose_from_album);//相冊選擇圖片按鈕
    picture = (ImageView) findViewById(R.id.photo_pictrue);         //圖片控件,用來顯示照片的。

    //打開相機拍照
    btnTakePhoto.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();
        }
        //android 7.0版本以下的系統,直接Uri.fromFile取得真實文件路徑;7.0及以上版本的系統,使用fileprovider封裝過的Uri再提供出去。
        if (Build.VERSION.SDK_INT >= 24) {
          imageUri = FileProvider.getUriForFile(MainActivity.this, "com.cofox.mycameraalbum.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);   //啟動Intent活動,拍完照會有結果返回到onActivityResult()方法中。
      }
    });

    //打開相冊選擇圖片
    btnChooseFromAlbum.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, @NonNull String[] permissions, @NonNull int[] grantResults) {
//    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode){
      case 1:
        if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
          openAlbum();
        }else{
          Toast.makeText(this, "You denied the permision.", Toast.LENGTH_LONG).show();
        }
        break;
      default:
    }
  }

  @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以下系統使用這個方法處理圖片
            handeleImageBeforeKitKat(data);
          }
        }
        break;
      default:
        break;
    }
  }

  @TargetApi(19)
  private void handleImageOnKitKat(Intent data) {
//    Toast.makeText(this,"到了handleImageOnKitKat(Intent data)方法了", Toast.LENGTH_LONG).show();
    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())){
        String id = docId.split(":")[1];//解析出數字格式的 id
        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 handeleImageBeforeKitKat(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_LONG).show();
    }
  }
}

看一下AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.cofox.mycameraalbum">
  <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:authorities="com.cofox.mycameraalbum.fileprovider"
      android:name="android.support.v4.content.FileProvider"
      android:exported="false"
      android:grantUriPermissions="true">
      <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
    </provider>
  </application>

</manifest>

上述就是小編為大家分享的android中怎么實現在相冊中選擇圖片了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女