• Android---打开相册选择图片


    简单实现打开系统相册选择一张图片并显示在UI上,适用与个人主页头像的切换。

    1. 添加存储权限。AndroidManifest.xml里添加读取内存的权限。

    1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    2. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

    2. 布局。布局内容比较交单,一个Button用来打开相册;一个ImageView用来接收从相册选择的图片。

    1. "1.0" encoding="utf-8"?>
    2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3. xmlns:tools="http://schemas.android.com/tools"
    4. android:layout_width="match_parent"
    5. android:layout_height="match_parent"
    6. tools:context=".MainActivity">
    7. <Button
    8. android:id="@+id/btn_open_gallery"
    9. android:layout_width="150dp"
    10. android:layout_height="75dp"
    11. android:layout_centerHorizontal="true"
    12. android:text="打开相册"
    13. android:textSize="20sp"/>
    14. <ImageView
    15. android:layout_width="wrap_content"
    16. android:layout_height="wrap_content"
    17. android:layout_centerHorizontal="true"
    18. android:layout_marginTop="10dp"
    19. android:layout_below="@+id/btn_open_gallery"/>
    20. RelativeLayout>

    3. 动态申请权限。Google 在 Android 6.0 开始引入了权限申请机制,除了再AndroidManifest.xml里申请静态权限,还需要在代码里动态申请。

    1. /**
    2. * 申请动态权限
    3. */
    4. private void applyPermission() {
    5. //检测权限
    6. if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
    7. != PackageManager.PERMISSION_GRANTED) {
    8. // 如果没有权限,则申请需要的权限
    9. ActivityCompat.requestPermissions(this,
    10. new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
    11. }else {
    12. // 已经申请了权限
    13. openGallery();
    14. }
    15. }

    4. 申请权限的回调。

    1. /**
    2. * 用户选择是否开启权限操作后的回调;TODO 同意/拒绝
    3. */
    4. @Override
    5. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    6. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    7. if (requestCode == PERMISSION_REQUEST_CODE) {
    8. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    9. // 用户同样授权
    10. openGallery();
    11. }else {
    12. // 用户拒绝授权
    13. Toast.makeText(this, "你拒绝使用存储权限!", Toast.LENGTH_SHORT).show();
    14. Log.d("HL", "你拒绝使用存储权限!");
    15. }
    16. }
    17. }

    5. 打开相册。

    1. /**
    2. * 打开相册
    3. */
    4. private void openGallery() {
    5. Intent intent = new Intent(Intent.ACTION_PICK, null);
    6. intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI , "image/*");
    7. startActivityForResult(intent, OPEN_GALLERY_REQUEST_CODE);
    8. }

    6. 结果回调。用户选择了一张图片,接收返回的结果并在ImageView里显示。、

    1. @Override
    2. protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    3. super.onActivityResult(requestCode, resultCode, data);
    4. if (requestCode == OPEN_GALLERY_REQUEST_CODE) { // 检测请求码
    5. if (resultCode == Activity.RESULT_OK && data != null) {
    6. try {
    7. InputStream inputStream = getContentResolver().openInputStream(data.getData());
    8. Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
    9. // TODO 把获取到的图片放到ImageView上
    10. mImg.setImageBitmap(bitmap);
    11. } catch (FileNotFoundException e) {
    12. e.printStackTrace();
    13. }
    14. }
    15. }
    16. }

    完整Demo

    1. package com.example.opengallery;
    2. import androidx.annotation.NonNull;
    3. import androidx.annotation.Nullable;
    4. import androidx.appcompat.app.AppCompatActivity;
    5. import androidx.core.app.ActivityCompat;
    6. import androidx.core.content.ContextCompat;
    7. import android.Manifest;
    8. import android.app.Activity;
    9. import android.content.Intent;
    10. import android.content.pm.PackageManager;
    11. import android.graphics.Bitmap;
    12. import android.graphics.BitmapFactory;
    13. import android.os.Bundle;
    14. import android.provider.MediaStore;
    15. import android.util.Log;
    16. import android.widget.Button;
    17. import android.widget.ImageView;
    18. import android.widget.Toast;
    19. import java.io.FileNotFoundException;
    20. import java.io.InputStream;
    21. public class MainActivity extends AppCompatActivity {
    22. private static final int PERMISSION_REQUEST_CODE = 0;
    23. private static final int OPEN_GALLERY_REQUEST_CODE = 1;
    24. private static final int TAKE_PHOTO_REQUEST_CODE = 2;
    25. private Button mOpenGallery;
    26. private ImageView mImg;
    27. @Override
    28. protected void onCreate(Bundle savedInstanceState) {
    29. super.onCreate(savedInstanceState);
    30. setContentView(R.layout.activity_main);
    31. mOpenGallery = findViewById(R.id.btn_open_gallery);
    32. mImg = findViewById(R.id.img);
    33. //打开相册
    34. mOpenGallery.setOnClickListener(v -> {
    35. applyPermission();
    36. });
    37. }
    38. /**
    39. * 申请动态权限
    40. */
    41. private void applyPermission() {
    42. //检测权限
    43. if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
    44. != PackageManager.PERMISSION_GRANTED) {
    45. // 如果没有权限,则申请需要的权限
    46. ActivityCompat.requestPermissions(this,
    47. new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
    48. }else {
    49. // 已经申请了权限
    50. openGallery();
    51. }
    52. }
    53. /**
    54. * 用户选择是否开启权限操作后的回调;TODO 同意/拒绝
    55. */
    56. @Override
    57. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    58. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    59. if (requestCode == PERMISSION_REQUEST_CODE) {
    60. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    61. // 用户同样授权
    62. openGallery();
    63. }else {
    64. // 用户拒绝授权
    65. Toast.makeText(this, "你拒绝使用存储权限!", Toast.LENGTH_SHORT).show();
    66. Log.d("HL", "你拒绝使用存储权限!");
    67. }
    68. }
    69. }
    70. /**
    71. * 打开相册
    72. */
    73. private void openGallery() {
    74. Intent intent = new Intent(Intent.ACTION_PICK, null);
    75. intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI , "image/*");
    76. startActivityForResult(intent, OPEN_GALLERY_REQUEST_CODE);
    77. }
    78. @Override
    79. protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    80. super.onActivityResult(requestCode, resultCode, data);
    81. if (requestCode == OPEN_GALLERY_REQUEST_CODE) { // 检测请求码
    82. if (resultCode == Activity.RESULT_OK && data != null) {
    83. try {
    84. InputStream inputStream = getContentResolver().openInputStream(data.getData());
    85. Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
    86. // TODO 把获取到的图片放到ImageView上
    87. mImg.setImageBitmap(bitmap);
    88. } catch (FileNotFoundException e) {
    89. e.printStackTrace();
    90. }
    91. }
    92. }
    93. }
    94. }

  • 相关阅读:
    迷茫中翻滚
    『现学现忘』Docker基础 — 33、Docker数据卷容器的说明与共享数据原理
    Java:代理模式详解
    数据增强功能工具,选项功能对照表
    人工智能新标准丨Whale 帷幄参与制定,助力信息安全产业建设
    aliexpress API 接入说明
    2065. 最大化一张图中的路径价值 Hard
    【Vue】params和query的区别?实战两种路由传参方式
    如何进行接口测试测?有哪些注意事项?保姆级解读
    动手学深度学习PyTorch(六):卷积神经网络
  • 原文地址:https://blog.csdn.net/qq_44950283/article/details/133074201