android - 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?
解决方案
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")
推荐阅读
- sql - 在 sql 中使用 LAG 跳过特定行
- ignite - 如果它是我自己的类型,Apache Ignite 会根据远程服务代理方法返回一个代理吗?
- php - 是否可以通过循环来优化PDO中的大量BindValue?
- php - 有没有办法从 mssql 增量导出到 mysql?
- hash - Apple Homekit 设置哈希
- symfony - Symfony 5 - 错误:服务“uri_signer”依赖于不存在的参数“kernel.secret”。您的意思是:“kernel.charset”吗?
- python - 根据第一个条目从数组中删除重复项
- runtime - 适用于 Ubuntu 14.04 的 OpenCL 运行时库
- numpy - AttributeError:“numpy.ndarray”对象没有属性“strip”
- javascript - Countdown Javascript Timer 不适用于平板电脑和手机,但适用于台式机