1.在activity里点击“获取照片”,然后跳转到系统相册:
fun open() {
var intent: Intent = Intent(“android.intent.action.GET_CONTENT”);
intent.setType(“image/*”);
startActivityForResult(intent, 1001);
}
2.返回拿到照片并显示:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
1001 -> {
var bitmap: Bitmap? = null
if (Build.VERSION.SDK_INT >= 19) {
bitmap = data?.let { ImgUtil.handleImageOnKitKat(this, it) }
} else {
bitmap = data?.let { ImgUtil.handleImageBeforeKitKat(this, it) };
}
val view: ImageView = binding.chooseImage
view.setImageBitmap(bitmap)
}
}
}
3.工具类(Kotlin):
package com.allynav.flatgroundsystem.util
import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.text.TextUtils
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
/**
*@author zd
*@time 2022/10/18 10:57
*@description : 获取系统照片并显示的工具类
*
**/
object ImgUtil {
fun handleImageOnKitKat(context: Context?, data: Intent): Bitmap? {
var imagePath = ""
var uri: Uri? = data.getData();
if (DocumentsContract.isDocumentUri(context, uri)) {
//如果是document类型的Uri,则通过document id处理
var docId: String = DocumentsContract.getDocumentId(uri);
if ("com.android.providers.media.documents" == uri?.authority) {
var id: String = docId.split(":")[1] //解析出数字格式的id
var selection: String = MediaStore.Images.Media._ID + "=" + id;
imagePath =
getImagePath(context!!, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection)
Log.e("jjjjjj", "image------" + imagePath )
} else if ("com.android.providers.downloads.documents" == uri?.authority) {
var contentUri: Uri = ContentUris.withAppendedId(
Uri.parse("content ://downloads/public_downloads"), docId.toLong()
)
imagePath = getImagePath(context!!, contentUri, null);
}
} else if ("content".equals(uri?.getScheme())) {
imagePath = getImagePath(context!!, uri, null)
return getImage(imagePath)
}
return getImage(imagePath)
}
fun handleImageBeforeKitKat(context: Context?, data: Intent): Bitmap? {
val uri = data.data
val imagePath = getImagePath(context!!, uri, null)
return getImage(imagePath)
}
private fun getImagePath(context: Context, uri: Uri?, selection: String?): String {
var path: String? = null
val cursor: Cursor? = context.contentResolver.query(uri!!, null, selection, null, null)
if (cursor != null) {
Log.e("jjjjjj", "image1------sds" + cursor.moveToFirst())
if (cursor.moveToFirst()) {
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))
Log.e("jjjjjj", "image2------sds" + path)
}
cursor.close()
}
return path.toString()
}
//传入图片路径,返回压缩后的bitmap
private fun getImage(srcPath: String?): Bitmap? {
if (TextUtils.isEmpty(srcPath)) //如果图片路径为空 直接返回
return null
val newOpts = BitmapFactory.Options()
//开始读入图片,此时把options.inJustDecodeBounds 设回true了
newOpts.inJustDecodeBounds = true
var bitmap = BitmapFactory.decodeFile(srcPath, newOpts) //此时返回bm为空
newOpts.inJustDecodeBounds = false
val w = newOpts.outWidth
val h = newOpts.outHeight
//现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
val hh = 800f //这里设置高度为800f
val ww = 480f //这里设置宽度为480f
//缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
var be = 1 //be=1表示不缩放
if (w > h && w > ww) { //如果宽度大的话根据宽度固定大小缩放
be = (newOpts.outWidth / ww).toInt()
} else if (w < h && h > hh) { //如果高度高的话根据宽度固定大小缩放
be = (newOpts.outHeight / hh).toInt()
}
if (be <= 0) be = 1
newOpts.inSampleSize = be //设置缩放比例
//重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
bitmap = BitmapFactory.decodeFile(srcPath, newOpts)
return compressImage(bitmap) //压缩好比例大小后再进行质量压缩
}
//对bitmap进行质量压缩
private fun compressImage(image: Bitmap): Bitmap? {
val baos = ByteArrayOutputStream()
image.compress(Bitmap.CompressFormat.JPEG, 100, baos) //质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
var options = 100
while (baos.toByteArray().toString().length / 1024 > 100) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩
baos.reset() //重置baos即清空baos
image.compress(
Bitmap.CompressFormat.JPEG,
options,
baos
) //这里压缩options%,把压缩后的数据存放到baos中
options -= 10 //每次都减少10
}
val isBm =
ByteArrayInputStream(baos.toByteArray()) //把压缩后的数据baos存放到ByteArrayInputStream中
return BitmapFactory.decodeStream(isBm, null, null) //把ByteArrayInputStream数据生成图片
}
}
4,放点xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.widget.Button
android:id="@+id/choose"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginStart="40dp"
android:layout_marginTop="72dp"
android:layout_marginEnd="40dp"
android:background="@drawable/wechat_bg"
android:gravity="center"
android:orientation="horizontal"
android:text="选择"
android:textColor="@color/ColorFFFFFF"
android:textSize="16sp" />
<ImageView
android:id="@+id/chooseImage"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_margin="80dp"
android:layout_below="@+id/choose"/>
</RelativeLayout>