如何压缩从科特林图库中挑选的照片

How to compress a photo picked from gallery in kotlin

我发现了很多关于该主题的问题,但 none 有一个完整的工作示例。

我的情况很简单:

  1. 获取图片
  2. 压缩图片
  3. 将压缩图像上传到 Firebase 存储

我现在的代码(没有压缩):

片段:

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        when (requestCode) {
            RC_PICK_IMAGE ->
                if (resultCode == Activity.RESULT_OK)
                    data?.data?.let { viewModel.updateUserPicture(it) }
        }
    }

视图模型:

    fun updatePhotoUrl(photoUrl: Uri?): Task<Void> =
        Storage.uploadFile("/$PS_USERS/$uid", photoUrl)
                    .continueWithTask { ... }

存储:(包装 Firebase 交互的对象)

    fun uploadFile(path: String, uri: Uri): Task<Uri> {
        val imageRef = storageRef.child(path)
        val uploadTask = imageRef.putFile(uri)

        // Return the task getting the download URL
        return uploadTask.continueWithTask { task ->
            if (!task.isSuccessful) {
                task.exception?.let {
                    throw it
                }
            }
            imageRef.downloadUrl
        }
    }

这非常有效。

现在我的问题是:在此过程中添加压缩的正确方法是什么?

最重要的是,这两种解决方案都需要上下文。我认为压缩是一个应该属于后端的过程(或 Repository class。在我的例子中是 Storage 对象),所以他们感觉有点不对劲。

有人可以分享这个简单用例的完整工作示例吗?

流程应该是:

  1. 用户选择图像并在 ImageView 中显示(scaleTyle 应该是 centerCrop ).

  2. 用户点击保存按钮,我们开始上传图片bytes,像这样:

     val uploadTask = profilePicturesReference.putBytes(getImageBytes())
    
     private fun getImageBytes(): ByteArray {
         val bitmap = Bitmap.createBitmap(my_profile_imageView.width, my_profile_imageView.height, Bitmap.Config.ARGB_8888)
    
         val canvas = Canvas(bitmap)
    
         my_profile_imageView.draw(canvas)
    
         val outputStream = ByteArrayOutputStream()
    
         bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)    //here, 100 is the quality in %
    
         return outputStream.toByteArray()
     }
    

演示:https://www.youtube.com/watch?v=iTXCn3NVqDM


将原始大小的图像上传到 Firebase 存储:

val uploadTask = profilePicturesReference.putFile(fileUri)
    

使用它可能会有所帮助: 通过传递 compressAndSetImage(data.data)

从 onActivityResult 调用 compressAndSetImage
fun compressAndSetImage(result: Uri){
        val job = Job()
        val uiScope = CoroutineScope(Dispatchers.IO + job)
        val fileUri = getFilePathFromUri(result, context!!) 
        uiScope.launch {
            val compressedImageFile = Compressor.compress(context!!, File(fileUri.path)){
                quality(50) // combine with compressor constraint
                format(Bitmap.CompressFormat.JPEG)
            }
            resultUri = Uri.fromFile(compressedImageFile)

            activity!!.runOnUiThread {
                resultUri?.let {
                    //set image here 
                }
            }
        }
    }

要解决此问题,我必须先将此路径转换为真实路径,这样我才能解决此问题。 首先,这是要在 build.gradle (app) 中添加的依赖项: //图片压缩依赖

implementation 'id.zelory:compressor:3.0.0'

//将uri路径转换为真实路径

@Throws(IOException::class)
fun getFilePathFromUri(uri: Uri?, context: Context?): Uri? {
    val fileName: String? = getFileName(uri, context)
    val file = File(context?.externalCacheDir, fileName)
    file.createNewFile()
    FileOutputStream(file).use { outputStream ->
        context?.contentResolver?.openInputStream(uri).use { inputStream ->
            copyFile(inputStream, outputStream)
            outputStream.flush()
        }
    }
    return Uri.fromFile(file)
}

@Throws(IOException::class)
private fun copyFile(`in`: InputStream?, out: OutputStream) {
    val buffer = ByteArray(1024)
    var read: Int? = null
    while (`in`?.read(buffer).also({ read = it!! }) != -1) {
        read?.let { out.write(buffer, 0, it) }
    }
}//copyFile ends

fun getFileName(uri: Uri?, context: Context?): String? {
    var fileName: String? = getFileNameFromCursor(uri, context)
    if (fileName == null) {
        val fileExtension: String? = getFileExtension(uri, context)
        fileName = "temp_file" + if (fileExtension != null) ".$fileExtension" else ""
    } else if (!fileName.contains(".")) {
        val fileExtension: String? = getFileExtension(uri, context)
        fileName = "$fileName.$fileExtension"
    }
    return fileName
}

fun getFileExtension(uri: Uri?, context: Context?): String? {
    val fileType: String? = context?.contentResolver?.getType(uri)
    return MimeTypeMap.getSingleton().getExtensionFromMimeType(fileType)
}

fun getFileNameFromCursor(uri: Uri?, context: Context?): String? {
    val fileCursor: Cursor? = context?.contentResolver
        ?.query(uri, arrayOf<String>(OpenableColumns.DISPLAY_NAME), null, null, null)
    var fileName: String? = null
    if (fileCursor != null && fileCursor.moveToFirst()) {
        val cIndex: Int = fileCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
        if (cIndex != -1) {
            fileName = fileCursor.getString(cIndex)
        }
    }
    return fileName
}

我能想到的最佳解决方案是:

片段:

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        when (requestCode) {
            RC_PICK_IMAGE ->
                if (resultCode == Activity.RESULT_OK)
                    data?.data?.let { uri ->
                        context?.let {
                        viewModel.updateUserPicture(uriToCompressedBitmap(it, uri)) 
                }
            }
        }
    }

    fun uriToCompressedBitmap(context: Context, uri: Uri): ByteArray {
        val pfd = context.contentResolver.openFileDescriptor(uri, "r")
        val bitmap =
            BitmapFactory.decodeFileDescriptor(pfd?.fileDescriptor, null, null)
        val baos = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 75, baos)
        return baos.toByteArray()
    }

(当然还有:updateUserPictureuploadFileUri 参数更改为 ByteArray,对 putFile 的调用更改为putBytes)

这个 link 对我很有帮助。

我不太喜欢在整个应用程序中使用位图而不是 uris,但这是迄今为止最适合我的方法。如果有人有更好的解决方案,请分享:)

编辑:

此解决方案存在元数据丢失问题,如所述. It is solvable of course (here), but I think that because the metadata fields can change between android versions, Hascher7's solution 更可靠。