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实现AVIF图片与其他图片格式间的批量转换

《Python实现AVIF图片与其他图片格式间的批量转换》这篇文章主要为大家详细介绍了如何使用Pillow库实现AVIF与其他格式的相互转换,即将AVIF转换为常见的格式,比如JPG或PNG,需要的小... 目录环境配置1.将单个 AVIF 图片转换为 JPG 和 PNG2.批量转换目录下所有 AVIF 图

详解如何通过Python批量转换图片为PDF

《详解如何通过Python批量转换图片为PDF》:本文主要介绍如何基于Python+Tkinter开发的图片批量转PDF工具,可以支持批量添加图片,拖拽等操作,感兴趣的小伙伴可以参考一下... 目录1. 概述2. 功能亮点2.1 主要功能2.2 界面设计3. 使用指南3.1 运行环境3.2 使用步骤4. 核

Java图片压缩三种高效压缩方案详细解析

《Java图片压缩三种高效压缩方案详细解析》图片压缩通常涉及减少图片的尺寸缩放、调整图片的质量(针对JPEG、PNG等)、使用特定的算法来减少图片的数据量等,:本文主要介绍Java图片压缩三种高效... 目录一、基于OpenCV的智能尺寸压缩技术亮点:适用场景:二、JPEG质量参数压缩关键技术:压缩效果对比

使用Python开发一个简单的本地图片服务器

《使用Python开发一个简单的本地图片服务器》本文介绍了如何结合wxPython构建的图形用户界面GUI和Python内建的Web服务器功能,在本地网络中搭建一个私人的,即开即用的网页相册,文中的示... 目录项目目标核心技术栈代码深度解析完整代码工作流程主要功能与优势潜在改进与思考运行结果总结你是否曾经

kotlin中const 和val的区别及使用场景分析

《kotlin中const和val的区别及使用场景分析》在Kotlin中,const和val都是用来声明常量的,但它们的使用场景和功能有所不同,下面给大家介绍kotlin中const和val的区别,... 目录kotlin中const 和val的区别1. val:2. const:二 代码示例1 Java

Python FastAPI+Celery+RabbitMQ实现分布式图片水印处理系统

《PythonFastAPI+Celery+RabbitMQ实现分布式图片水印处理系统》这篇文章主要为大家详细介绍了PythonFastAPI如何结合Celery以及RabbitMQ实现简单的分布式... 实现思路FastAPI 服务器Celery 任务队列RabbitMQ 作为消息代理定时任务处理完整

使用C#代码在PDF文档中添加、删除和替换图片

《使用C#代码在PDF文档中添加、删除和替换图片》在当今数字化文档处理场景中,动态操作PDF文档中的图像已成为企业级应用开发的核心需求之一,本文将介绍如何在.NET平台使用C#代码在PDF文档中添加、... 目录引言用C#添加图片到PDF文档用C#删除PDF文档中的图片用C#替换PDF文档中的图片引言在当

详解C#如何提取PDF文档中的图片

《详解C#如何提取PDF文档中的图片》提取图片可以将这些图像资源进行单独保存,方便后续在不同的项目中使用,下面我们就来看看如何使用C#通过代码从PDF文档中提取图片吧... 当 PDF 文件中包含有价值的图片,如艺术画作、设计素材、报告图表等,提取图片可以将这些图像资源进行单独保存,方便后续在不同的项目中使

Kotlin 作用域函数apply、let、run、with、also使用指南

《Kotlin作用域函数apply、let、run、with、also使用指南》在Kotlin开发中,作用域函数(ScopeFunctions)是一组能让代码更简洁、更函数式的高阶函数,本文将... 目录一、引言:为什么需要作用域函数?二、作用域函China编程数详解1. apply:对象配置的 “流式构建器”最

Android中Dialog的使用详解

《Android中Dialog的使用详解》Dialog(对话框)是Android中常用的UI组件,用于临时显示重要信息或获取用户输入,本文给大家介绍Android中Dialog的使用,感兴趣的朋友一起... 目录android中Dialog的使用详解1. 基本Dialog类型1.1 AlertDialog(