首页 > 解决方案 > Create Zip file where the contents are a bitmaps for Android Kotlin

问题描述

I am currently writing an app where I need to create a zip file that has a bunch of bitmap images in it. I have a List that has the Uri's for all the images.

Could someone please direct me to how I can create a new zip file and then add all the images to a newly created zip file?

标签: androidkotlinzipfile

解决方案


Assuming you have external storage permissions granted following should work

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

Remember this is an extension function on Context so it will require to be called with a context like context.zip(listOfUris, "ZIP_FILE_NAME_HERE")


推荐阅读