Pick image from sd card, resize the image and save it back to sd card

前端 未结 6 1343
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 14:11

I am working on an application, in which I need to pick an image from sd card and show it in image view. Now I want the user to decrease/increase its width by c

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-13 14:52

    Solution without OutOfMemoryException in Kotlin

    fun resizeImage(file: File, scaleTo: Int = 1024) {
        val bmOptions = BitmapFactory.Options()
        bmOptions.inJustDecodeBounds = true
        BitmapFactory.decodeFile(file.absolutePath, bmOptions)
        val photoW = bmOptions.outWidth
        val photoH = bmOptions.outHeight
    
        // Determine how much to scale down the image
        val scaleFactor = Math.min(photoW / scaleTo, photoH / scaleTo)
    
        bmOptions.inJustDecodeBounds = false
        bmOptions.inSampleSize = scaleFactor
    
        val resized = BitmapFactory.decodeFile(file.absolutePath, bmOptions) ?: return
        file.outputStream().use {
            resized.compress(Bitmap.CompressFormat.JPEG, 75, it)
            resized.recycle()
        }
    }
    

提交回复
热议问题