**
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
}
本文档介绍了在Android 10及以上版本如何使用新API获取Pictures目录的照片,并演示了如何通过 BitmapFactory进行图片压缩,确保在不同设备上流畅显示。

1036

被折叠的 条评论
为什么被折叠?



