重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

Android实现选择相册图片并显示功能

本文实例为大家分享了Android实现选择相册图片并显示的具体代码,供大家参考,具体内容如下

目前创新互联公司已为成百上千家的企业提供了网站建设、域名、网络空间、网站运营、企业网站设计、郾城网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。

需求描述: 选择手机相册中的一张图片,并通过ImageView展示出来
参考博文: android打开手机相册获取真正的图片路径

效果展示:

Android实现选择相册图片并显示功能

示例代码:

MainActivity

package com.example.www.mutilmedia;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

  String[] mPermissionList = new String[]{
      Manifest.permission.WRITE_EXTERNAL_STORAGE,
      Manifest.permission.READ_EXTERNAL_STORAGE};
  public static final int REQUEST_PICK_IMAGE = 11101;
  private ImageView mShowImg;

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

    mShowImg = (ImageView) findViewById(R.id.imageView);

  }

  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
      case 100:
        boolean writeExternalStorage = grantResults[0] == PackageManager.PERMISSION_GRANTED;
        boolean readExternalStorage = grantResults[1] == PackageManager.PERMISSION_GRANTED;
        Log.e("MainActivity", Arrays.toString(grantResults));
        if (grantResults.length > 0 && writeExternalStorage && readExternalStorage) {
          getImage();
        } else {
          Toast.makeText(this, "请设置必要权限", Toast.LENGTH_SHORT).show();
        }

        break;
    }
  }

  private void getImage() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
      startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"),
          REQUEST_PICK_IMAGE);
    } else {
      Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
      intent.addCategory(Intent.CATEGORY_OPENABLE);
      intent.setType("image/*");
      startActivityForResult(intent, REQUEST_PICK_IMAGE);
    }
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
      switch (requestCode) {
        case REQUEST_PICK_IMAGE:
          if (data != null) {
            String realPathFromUri = RealPathFromUriUtils.getRealPathFromUri(this, data.getData());
            Log.e("MainActivity", realPathFromUri);
            showImg(realPathFromUri);
          } else {
            Toast.makeText(this, "图片损坏,请重新选择", Toast.LENGTH_SHORT).show();
          }

          break;
      }
    }
  }


  public void openCamera(View view) {
    ActivityCompat.requestPermissions(MainActivity.this, mPermissionList, 100);
  }


  public void showImg(String path){
    Bitmap bitmap = BitmapFactory.decodeFile(path);
    mShowImg.setImageBitmap(bitmap);
  }

}

RealPathFromUriUtils

package com.example.www.mutilmedia;

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

public class RealPathFromUriUtils {
  /**
   * 根据Uri获取图片的绝对路径
   *
   * @param context 上下文对象
   * @param uri   图片的Uri
   * @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
   */
  public static String getRealPathFromUri(Context context, Uri uri) {
    int sdkVersion = Build.VERSION.SDK_INT;
    if (sdkVersion >= 19) { // api >= 19
      return getRealPathFromUriAboveApi19(context, uri);
    } else { // api < 19
      return getRealPathFromUriBelowAPI19(context, uri);
    }
  }

  /**
   * 适配api19以下(不包括api19),根据uri获取图片的绝对路径
   *
   * @param context 上下文对象
   * @param uri   图片的Uri
   * @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
   */
  private static String getRealPathFromUriBelowAPI19(Context context, Uri uri) {
    return getDataColumn(context, uri, null, null);
  }

  /**
   * 适配api19及以上,根据uri获取图片的绝对路径
   *
   * @param context 上下文对象
   * @param uri   图片的Uri
   * @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
   */
  @SuppressLint("NewApi")
  private static String getRealPathFromUriAboveApi19(Context context, Uri uri) {
    String filePath = null;
    if (DocumentsContract.isDocumentUri(context, uri)) {
      // 如果是document类型的 uri, 则通过document id来进行处理
      String documentId = DocumentsContract.getDocumentId(uri);
      if (isMediaDocument(uri)) { // MediaProvider
        // 使用':'分割
        String id = documentId.split(":")[1];

        String selection = MediaStore.Images.Media._ID + "=?";
        String[] selectionArgs = {id};
        filePath = getDataColumn(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, selectionArgs);
      } else if (isDownloadsDocument(uri)) { // DownloadsProvider
        Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
        filePath = getDataColumn(context, contentUri, null, null);
      }
    } else if ("content".equalsIgnoreCase(uri.getScheme())) {
      // 如果是 content 类型的 Uri
      filePath = getDataColumn(context, uri, null, null);
    } else if ("file".equals(uri.getScheme())) {
      // 如果是 file 类型的 Uri,直接获取图片对应的路径
      filePath = uri.getPath();
    }
    return filePath;
  }

  /**
   * 获取数据库表中的 _data 列,即返回Uri对应的文件路径
   *
   * @return
   */
  private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
    String path = null;

    String[] projection = new String[]{MediaStore.Images.Media.DATA};
    Cursor cursor = null;
    try {
      cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
      if (cursor != null && cursor.moveToFirst()) {
        int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
        path = cursor.getString(columnIndex);
      }
    } catch (Exception e) {
      if (cursor != null) {
        cursor.close();
      }
    }
    return path;
  }

  /**
   * @param uri the Uri to check
   * @return Whether the Uri authority is MediaProvider
   */
  private static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
  }

  /**
   * @param uri the Uri to check
   * @return Whether the Uri authority is DownloadsProvider
   */
  private static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
  }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


  

  

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>


  
  

  
    
      
        

        
      
    
  

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。


网站题目:Android实现选择相册图片并显示功能
链接URL:http://cqcxhl.com/article/iiigsg.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP