【问题标题】:How to compare bytearray to the file.length() in kotlin?如何将 bytearray 与 kotlin 中的 file.length() 进行比较?
【发布时间】:2020-04-04 12:21:44
【问题描述】:
  1. 我只需要发送小于 2 mb 的文件。我使用文件和位图。项目中使用了easyimage库。

  2. 当我除以 1024 时,如何比较常规 imagefile.length() 返回以 kb 为单位。但位图图像返回字节 bitmap.bytecount

  3. 如何获取位图文件的 kb 值?它循环直到完全压缩到 0 质量。

代码: 变量质量 = 90

var imgKiloByteLength = imageFile.length() / 1024
var imgMegaByteLength = imgKiloByteLength / 1024  //returns in mb

if (imgKiloByteLength > 2048) {
   while (imgKiloByteLength > 2048) {  //reducing the quality until it comes under 2mb
     var compressedBitmap = compressBitmap(bitmap, quality)
     bitmap = compressedBitmap
     Log.e("result",bitmap.getByteCount().toString())
     Glide.with(this@EditProfileActivity).load(bitmap).into(profileImage)
     Log.e("result", "image more than 2mb ${imgKiloByteLength}")
     quality -= 10
   }
} else {
   Glide.with(this@EditProfileActivity).load(bitmap).into(profileImage)
   Log.e("result", "image size ok ${imgKiloByteLength}")
}

我能做什么? 提前致谢。

【问题讨论】:

  • 我没有看到文件。我不明白你想把它寄到哪里。
  • 也许你在这里找到问题 3 的答案stackoverflow.com/questions/51919925/…
  • 您没有在 while 循环中更新 imgKiloByteLength,因此 imgKiloByteLength 的值将保持与循环开始之前的值相同。意味着它是一个无限循环。

标签: android file kotlin


【解决方案1】:

此代码可以帮助您将位图文件压缩到最大尺寸

object BitmapUtils {
    const val ONE_KIO = 1024
    const val ONE_MIO = ONE_KIO * ONE_KIO

    /**
     * Compress, if needed, an image file to be lower than or equal to 1 Mio
     *
     * @param filePath Image file path
     *
     * @return Stream containing data of the compressed image. Can be null
     */
    fun compressedImageFile(filePath: String): InputStream? {
        var quality = 100
        var inputStream: InputStream? = null
        if (filePath.isNotEmpty()) {
            var bufferSize = Integer.MAX_VALUE
            val byteArrayOutputStream = ByteArrayOutputStream()
            try {
                val bitmap = BitmapFactory.decodeFile(filePath)
                do {
                    if (bitmap != null) {
                        byteArrayOutputStream.reset()
                        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, byteArrayOutputStream)
                        bufferSize = byteArrayOutputStream.size()
                        logD { "quality: $quality -> length: $bufferSize" }
                        quality -= 10
                    }
                } while (bufferSize > ONE_MIO)
                inputStream = ByteArrayInputStream(byteArrayOutputStream.toByteArray())
                byteArrayOutputStream.close()
            } catch (e: Exception) {
                logE { "Exception when compressing file image: ${e.message}" }
            }
        }
        return inputStream
    }
}

不要关心logX方法,它们是我方便的日志方法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-05
    • 2013-11-20
    • 2015-10-20
    • 1970-01-01
    相关资源
    最近更新 更多