欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-11-14 14:22:10
本文实例为大家分享了android实现选择相册图片并显示的具体代码,供大家参考,具体内容如下 需求描述: 选择手机相册中的一张图片,并通过imageview展示出来 参...

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

需求描述: 选择手机相册中的一张图片,并通过imageview展示出来
参考博文:

效果展示:

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"?>
<android.support.constraint.constraintlayout 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:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".mainactivity">

  <imageview
    android:id="@+id/imageview"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginstart="8dp"
    android:layout_margintop="8dp"
    android:layout_marginend="8dp"
    android:layout_marginbottom="8dp"
    app:layout_constraintbottom_tobottomof="parent"
    app:layout_constraintend_toendof="parent"
    app:layout_constraintstart_tostartof="parent"
    app:layout_constrainttop_tobottomof="@+id/button3"
    app:srccompat="@android:color/white" />

  <button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginstart="8dp"
    android:layout_margintop="16dp"
    android:layout_marginend="8dp"
    android:onclick="opencamera"
    android:text="camera"
    app:layout_constraintend_toendof="parent"
    app:layout_constrainthorizontal_bias="0.048"
    app:layout_constraintstart_tostartof="parent"
    app:layout_constrainttop_totopof="parent" />

</android.support.constraint.constraintlayout>

androidmanifest.xml

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

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

</manifest>

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