**
Android访问DIRECTORY_PICTURES,压缩并显示
**
图片读取在Api29上有了变化
private fun getPath(): String {
return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).path
} else {
getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.path ?: ""
}
}
#读取图片,压缩
private fun compressPicture(){
val option = BitmapFactory.Options()
//只读宽高 不加载图片 避免大图片oom
option.inJustDecodeBounds = true
val path = getPath()+"/launcher_ic.png"
val file = BitmapFactory.decodeFile(path,option)
if (file == null){
Log.w(TAG,"file 是空的 没有返回图片 返回的是图片的宽高 w:${option.outWidth} h:${option.outHeight}")
}
option.inSampleSize = calculateInSampleSize(option,50,50)
option.inJustDecodeBounds = false
val reallyBitmap = BitmapFactory.decodeFile(path,option)
if (reallyBitmap == null){
Log.w("AAA","reallyBitmap == null")
}else{
binding.ivNewBitmap.setImageBitmap(reallyBitmap)
}
}
private fun calculateInSampleSize(option: BitmapFactory.Options, with: Int, height: Int) : Int {
val oldWith = option.outWidth
val oldHeight = option.outHeight
var inSampleSize = 1
if (oldWith > with || oldHeight > height){
val oldWithRatio = (oldWith / with.toDouble()).roundToInt()
val oldHeightRatio = (oldHeight / height.toDouble()).roundToInt()
inSampleSize = if (oldHeightRatio > oldWithRatio) oldWithRatio else oldWithRatio
val totalBitmapPixels = oldHeight * oldWith
val targetBitmapPixels = with * height * 2
while (totalBitmapPixels / (inSampleSize * inSampleSize) > targetBitmapPixels){
inSampleSize ++
}
}
return inSampleSize
}