如何压缩从 kotlin 画廊中挑选的照片

如何解决如何压缩从 kotlin 画廊中挑选的照片

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

我的情况很简单:

  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
        }
    }

这很完美。

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

  • 我找到了许多指向 Compressor 库(例如 herehere)的答案并尝试了它,但它不适用于图库结果 uri。我找到了从中获取实际 uri 的方法(例如 here),但它们感觉像是大量样板代码,因此感觉这不是最佳实践。
  • 我还使用 bitmap.compress(如 herehere)找到了许多答案,也尝试过,但它要求提供位图。使用 MediaStore.Images.Media.getBitmap 获取位图很容易,但它已被弃用,this 解决方案让我怀疑这是否是正确的方向。此外,将位图保存在我的 LiveData 对象中(在实际保存之前显示在屏幕上,在编辑屏幕中),而不是 uri,感觉很奇怪(我使用 Glide 来呈现图像)。

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

有人可以分享这个微不足道的用例的完整工作示例吗?

解决方法

使用它可能会有所帮助: 通过传递 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,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)
    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
}
,

流程应该是:

  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)
    
,

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

片段:

    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)
        val baos = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG,75,baos)
        return baos.toByteArray()
    }

(当然:UriupdateUserPictureuploadFile 参数更改为 ByteArray,对 putFile 的调用更改为 {{ 1}})

这个link对我很有帮助。

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

编辑:

此解决方案会丢失元数据,如所描述的 here。它当然是可以解决的(here),但我认为因为元数据字段可以在 android 版本之间改变,所以 Hascher7 的解决方案 above 更健壮。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-