创建 Zip 文件,其中内容是 Android Kotlin 的位图

Create Zip file where the contents are a bitmaps for Android Kotlin

我目前正在编写一个应用程序,我需要在其中创建一个包含一堆位图图像的 zip 文件。我有一个列表,其中包含所有图像的 Uri。

有人可以指导我如何创建新的 zip 文件,然后将所有图像添加到新创建的 zip 文件吗?

假设您已授予外部存储权限,以下应该有效

val BUFFER = 1024
fun Context.zip(files: Array<Uri>, zipFileName: String?) {
    try {
        var origin: BufferedInputStream? = null
        val dest = FileOutputStream(zipFileName)
        val out = ZipOutputStream(BufferedOutputStream(dest))
        val data = ByteArray(BUFFER)
        for (uri in files) {
            val stringUri = uri.toString()
            val fi = openFileInput(stringUri)
            origin = BufferedInputStream(fi, BUFFER)
            val entry = ZipEntry(stringUri.substring(stringUri.lastIndexOf("/") + 1))
            out.putNextEntry(entry)
            var count: Int
            while (origin.read(data, 0, BUFFER).also { count = it } != -1) {
                out.write(data, 0, count)
            }
            origin.close()
        }
        out.close()
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

请记住,这是 Context 的扩展函数,因此需要使用类似 context.zip(listOfUris, "ZIP_FILE_NAME_HERE")

的上下文来调用它