Android 图片读取 压缩显示

**

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
    }

附上github地址

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值