Android實(shí)現(xiàn)選擇相冊(cè)圖片并顯示功能
本文實(shí)例為大家分享了Android實(shí)現(xiàn)選擇相冊(cè)圖片并顯示的具體代碼,供大家參考,具體內(nèi)容如下
需求描述: 選擇手機(jī)相冊(cè)中的一張圖片,并通過(guò)ImageView展示出來(lái)
參考博文: android打開(kāi)手機(jī)相冊(cè)獲取真正的圖片路徑
效果展示:

示例代碼:
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, "請(qǐng)?jiān)O(shè)置必要權(quán)限", 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, "圖片損壞,請(qǐng)重新選擇", 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 {
/**
* 根據(jù)Uri獲取圖片的絕對(duì)路徑
*
* @param context 上下文對(duì)象
* @param uri 圖片的Uri
* @return 如果Uri對(duì)應(yīng)的圖片存在, 那么返回該圖片的絕對(duì)路徑, 否則返回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),根據(jù)uri獲取圖片的絕對(duì)路徑
*
* @param context 上下文對(duì)象
* @param uri 圖片的Uri
* @return 如果Uri對(duì)應(yīng)的圖片存在, 那么返回該圖片的絕對(duì)路徑, 否則返回null
*/
private static String getRealPathFromUriBelowAPI19(Context context, Uri uri) {
return getDataColumn(context, uri, null, null);
}
/**
* 適配api19及以上,根據(jù)uri獲取圖片的絕對(duì)路徑
*
* @param context 上下文對(duì)象
* @param uri 圖片的Uri
* @return 如果Uri對(duì)應(yīng)的圖片存在, 那么返回該圖片的絕對(duì)路徑, 否則返回null
*/
@SuppressLint("NewApi")
private static String getRealPathFromUriAboveApi19(Context context, Uri uri) {
String filePath = null;
if (DocumentsContract.isDocumentUri(context, uri)) {
// 如果是document類型的 uri, 則通過(guò)document id來(lái)進(jìn)行處理
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,直接獲取圖片對(duì)應(yīng)的路徑
filePath = uri.getPath();
}
return filePath;
}
/**
* 獲取數(shù)據(jù)庫(kù)表中的 _data 列,即返回Uri對(duì)應(yīng)的文件路徑
*
* @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>
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android實(shí)現(xiàn)圖片自動(dòng)輪播并且支持手勢(shì)左右無(wú)限滑動(dòng)
這篇文章給大家介紹android實(shí)現(xiàn)圖片自動(dòng)輪播并且支持手勢(shì)左右無(wú)限滑動(dòng),代碼簡(jiǎn)單易懂,非常不錯(cuò),具有參考借鑒價(jià)值,感興趣的朋友一起看看吧2016-10-10
Android實(shí)現(xiàn)帶指示器的自動(dòng)輪播式ViewPager
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)帶指示器的自動(dòng)輪播式ViewPager的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-02-02
Flutter音樂(lè)播放插件audioplayers使用步驟詳解
audioplayers是一個(gè)可以支持同時(shí)播放多個(gè)音頻文件的Flutter的插件,可以播放多個(gè)同時(shí)的音頻文件,這篇文章主要介紹了audioplayers的使用步驟,感興趣想要詳細(xì)了解可以參考下文2023-05-05
Android中使用Canvas繪制南丁格爾玫瑰圖(Nightingale rose diagram)
這篇文章主要介紹了Android中使用Canvas繪制南丁格爾玫瑰圖(Nightingale rose diagram),本文直接給出實(shí)現(xiàn)代碼和運(yùn)行效果圖,需要的朋友可以參考下2015-03-03
Android中TextView實(shí)現(xiàn)超過(guò)固定行數(shù)顯示“...展開(kāi)全部”
這篇文章主要給大家介紹了關(guān)于Android中TextView如何實(shí)現(xiàn)超過(guò)固定行數(shù)顯示"...展開(kāi)全部"的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-12-12
Android設(shè)備adb連接后顯示device unauthorized解決方案
這篇文章主要為大家介紹了Android設(shè)備adb連接后顯示device unauthorized解決方案詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06

