Android Kotlin 打开相册选择图片(多选)

2024-06-02 07:28

本文主要是介绍Android Kotlin 打开相册选择图片(多选),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1. 核心代码

打开系统相册功能,本代码使用两种方式打开本地相册,startActivityForResult 已经废弃,可以使用新的方式。

package com.example.facedetectordemoimport android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.facedetectordemo.databinding.ActivityMainBinding
import com.example.facedetectordemo.entity.FaceInfo
import android.Manifest;
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.Activity
import android.content.ContentUris
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.provider.DocumentsContract
import android.provider.MediaStore
import com.google.android.material.snackbar.Snackbarclass MainActivity : AppCompatActivity() {private lateinit var binding: ActivityMainBindingprivate val CHOOSE_PHOTO = 1private val requestPermissionLauncher =registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->if (isGranted) {Log.i("Permission: ", "Granted")} else {Log.i("Permission: ", "Denied")}}private val launcherActivity = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {val data = it.dataif (it.resultCode == Activity.RESULT_OK) {// 判断手机系统版本号if (Build.VERSION.SDK_INT >= 19) {// 4.4及以上系统使用这个方法处理图片if (data != null) {if(data.clipData != null) {handleImageOnKitKat(data.clipData!!.getItemAt(0).uri)} else if(data.data != null) {handleImageOnKitKat(data.data!!)}}}}}override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)binding = ActivityMainBinding.inflate(layoutInflater)setContentView(binding.root)// Example of a call to a native methodbinding.openGallery.setOnClickListener{val intent = Intent("android.intent.action.GET_CONTENT")intent.type = "image/*" // */intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)//startActivityForResult(intent, CHOOSE_PHOTO) // 打开相册, 废弃APIlauncherActivity.launch(intent)}val infos = getFaceInfoList()Log.d("zhouyong", "onCreate: size " + infos.size)requestPermission();}override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {super.onActivityResult(requestCode, resultCode, data)when (requestCode) {CHOOSE_PHOTO -> if (resultCode == Activity.RESULT_OK) {// 判断手机系统版本号if (Build.VERSION.SDK_INT >= 19) {// 4.4及以上系统使用这个方法处理图片if (data != null) {if(data.clipData != null) {handleImageOnKitKat(data.clipData!!.getItemAt(0).uri)} else if(data.data != null) {handleImageOnKitKat(data.data!!)}}} else {}}else -> {}}}@TargetApi(19)private fun handleImageOnKitKat(uri: Uri) {var imagePath: String? = null//val uri = data.dataLog.d("TAG", "handleImageOnKitKat: uri is $uri")if (DocumentsContract.isDocumentUri(this, uri)) {// 如果是document类型的Uri,则通过document id处理val docId = DocumentsContract.getDocumentId(uri)if ("com.android.providers.media.documents" == uri!!.authority) {val id = docId.split(":".toRegex()).toTypedArray()[1] // 解析出数字格式的idval selection = MediaStore.Images.Media._ID + "=" + idimagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection)} else if ("com.android.providers.downloads.documents" == uri.authority) {val contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), java.lang.Long.valueOf(docId))imagePath = getImagePath(contentUri, null)}} else if ("content".equals(uri!!.scheme, ignoreCase = true)) {// 如果是content类型的Uri,则使用普通方式处理imagePath = getImagePath(uri, null)} else if ("file".equals(uri.scheme, ignoreCase = true)) {// 如果是file类型的Uri,直接获取图片路径即可imagePath = uri.path}displayImage(imagePath) // 根据图片路径显示图片}@SuppressLint("Range")private fun getImagePath(uri: Uri?, selection: String?): String? {var path: String? = null// 通过Uri和selection来获取真实的图片路径val cursor = contentResolver.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 fun displayImage(imagePath: String?) {if (imagePath != null) {val bitmap = BitmapFactory.decodeFile(imagePath)binding.imageView.setImageBitmap(bitmap)} else {//Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show()}}fun requestPermission() {when {ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED -> {}ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.CAMERA) -> {requestPermissionLauncher.launch(Manifest.permission.CAMERA)requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)requestPermissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)}else -> {requestPermissionLauncher.launch(Manifest.permission.CAMERA)requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)requestPermissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)}}}fun View.showSnackbar(view: View,msg: String,length: Int,actionMessage: CharSequence?,action: (View) -> Unit) {val snackbar = Snackbar.make(view, msg, length)if (actionMessage != null) {snackbar.setAction(actionMessage) {action(this)}.show()} else {snackbar.show()}}/*** A native method that is implemented by the 'facedetectordemo' native library,* which is packaged with this application.*/external fun stringFromJNI(): Stringexternal fun getFaceInfoList(): Array<FaceInfo>companion object {// Used to load the 'facedetectordemo' library on application startup.init {System.loadLibrary("facedetectordemo")}}
}

2. main_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"><Buttonandroid:id="@+id/openGallery"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginBottom="212dp"android:text="打开相册"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintHorizontal_bias="0.498"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/imageView"app:layout_constraintVertical_bias="1.0" /><ImageViewandroid:id="@+id/imageView"android:layout_width="200dp"android:layout_height="200dp"android:layout_marginTop="96dp"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent"tools:srcCompat="@tools:sample/avatars" /></androidx.constraintlayout.widget.ConstraintLayout>

这篇关于Android Kotlin 打开相册选择图片(多选)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1023322

相关文章

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

Python基于微信OCR引擎实现高效图片文字识别

《Python基于微信OCR引擎实现高效图片文字识别》这篇文章主要为大家详细介绍了一款基于微信OCR引擎的图片文字识别桌面应用开发全过程,可以实现从图片拖拽识别到文字提取,感兴趣的小伙伴可以跟随小编一... 目录一、项目概述1.1 开发背景1.2 技术选型1.3 核心优势二、功能详解2.1 核心功能模块2.

Go语言如何判断两张图片的相似度

《Go语言如何判断两张图片的相似度》这篇文章主要为大家详细介绍了Go语言如何中实现判断两张图片的相似度的两种方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 在介绍技术细节前,我们先来看看图片对比在哪些场景下可以用得到:图片去重:自动删除重复图片,为存储空间"瘦身"。想象你是一个

使用Python实现base64字符串与图片互转的详细步骤

《使用Python实现base64字符串与图片互转的详细步骤》要将一个Base64编码的字符串转换为图片文件并保存下来,可以使用Python的base64模块来实现,这一过程包括解码Base64字符串... 目录1. 图片编码为 Base64 字符串2. Base64 字符串解码为图片文件3. 示例使用注意

Android学习总结之Java和kotlin区别超详细分析

《Android学习总结之Java和kotlin区别超详细分析》Java和Kotlin都是用于Android开发的编程语言,它们各自具有独特的特点和优势,:本文主要介绍Android学习总结之Ja... 目录一、空安全机制真题 1:Kotlin 如何解决 Java 的 NullPointerExceptio

VS配置好Qt环境之后但无法打开ui界面的问题解决

《VS配置好Qt环境之后但无法打开ui界面的问题解决》本文主要介绍了VS配置好Qt环境之后但无法打开ui界面的问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 目UKeLvb录找到Qt安装目录中designer.UKeLvBexe的路径找到vs中的解决方案资源

c/c++的opencv实现图片膨胀

《c/c++的opencv实现图片膨胀》图像膨胀是形态学操作,通过结构元素扩张亮区填充孔洞、连接断开部分、加粗物体,OpenCV的cv::dilate函数实现该操作,本文就来介绍一下opencv图片... 目录什么是图像膨胀?结构元素 (KerChina编程nel)OpenCV 中的 cv::dilate() 函

Kotlin Compose Button 实现长按监听并实现动画效果(完整代码)

《KotlinComposeButton实现长按监听并实现动画效果(完整代码)》想要实现长按按钮开始录音,松开发送的功能,因此为了实现这些功能就需要自己写一个Button来解决问题,下面小编给大... 目录Button 实现原理1. Surface 的作用(关键)2. InteractionSource3.

使用Python实现调用API获取图片存储到本地的方法

《使用Python实现调用API获取图片存储到本地的方法》开发一个自动化工具,用于从JSON数据源中提取图像ID,通过调用指定API获取未经压缩的原始图像文件,并确保下载结果与Postman等工具直接... 目录使用python实现调用API获取图片存储到本地1、项目概述2、核心功能3、环境准备4、代码实现

Java实现图片淡入淡出效果

《Java实现图片淡入淡出效果》在现代图形用户界面和游戏开发中,**图片淡入淡出(FadeIn/Out)**是一种常见且实用的视觉过渡效果,它可以用于启动画面、场景切换、轮播图、提示框弹出等场景,通过... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细