android - 在 Android 中将图像压缩到 200KB 字节大小
问题描述
我尝试使用我的代码将大于 3MB的大尺寸图像压缩 到200BK。但它不起作用。尽管我把任何质量,输出总是具有相同的结果。我不知道我错在哪里。 请告诉我我的错误。 我只想转换PNG。MAX_SIZE_UPLOAD = 200KB。前任:
input: 4900000, quality: 90 output = 32000000
input: 4900000, quality: 80 output = 32000000
override fun compress(file: File): Single<File> {
val result: SingleSubject<File> = SingleSubject.create()
val options = RequestOptions()
val optionsBitmap = BitmapFactory.Options()
val originSize = file.length()
optionsBitmap.inJustDecodeBounds = true
BitmapFactory.decodeFile(file.absolutePath, optionsBitmap)
Glide.with(context)
.asBitmap().load(file)
.into(object : SimpleTarget<Bitmap>() {
override fun onLoadFailed(errorDrawable: Drawable?) {
super.onLoadFailed(errorDrawable)
}
override fun onResourceReady(
resource: Bitmap,
transition: com.bumptech.glide.request.transition.Transition<in Bitmap>?
) {
thread {
try {
val stream = ByteArrayOutputStream()
val quality = ((100 * MAX_SIZE_UPLOAD) / file.length())
resource.compress(Bitmap.CompressFormat.PNG, quality.toInt(), stream)
saveFileToCacheDir(stream.toByteArray())
.observeOnUiThread()
.subscribe({
result.onSuccess(it)
}, {
result.onError(Throwable())
})
} catch (e: Exception) {
result.onError(Throwable())
}
}
}
})
return result
}
override fun saveFileToCacheDir(data: ByteArray): Single<File> {
val result: SingleSubject<File> = SingleSubject.create()
try {
val file = File(context.cacheDir, "$FILE_NAME${System.currentTimeMillis()}")
file.createNewFile()
val fos = FileOutputStream(file)
fos.write(data)
fos.flush()
fos.close()
result.onSuccess(file)
} catch (e: IOException) {
result.onError(e)
}
return result
}
解决方案
这是将图像位图压缩到文件的解决方案。
fun bitmapToFile(bitmap: Bitmap, context: Context): String {
// Get the context wrapper
val wrapper = ContextWrapper(context)
// Initialize a new file instance to save bitmap object
var file = wrapper.getDir("Images", Context.MODE_PRIVATE)
file = File(file, "${UUID.randomUUID()}.jpg")
try {
val stream: OutputStream = FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.JPEG,15,stream)
stream.flush()
stream.close()
} catch (e: IOException) {
e.printStackTrace()
}
// Return the saved bitmap uri
return file.absolutePath
}
推荐阅读
- ios - 在 Swift 5 中自动生成强密码
- php - 在 Ubuntu 16.04 上安装 mysql-server-5.6 时出现问题
- gcc - GCC Linker:如何在输出部分生成每个文件贡献的报告
- reactjs - 在 React JS 中多次使用一个组件
- angular - Angular 8 响应缺少 _body 和 headers
- swift - 创建通用基础 XCTestCase 不算作覆盖代码
- mysql - AWS RDS MySQL 性能问题
- oracle - INS-20802 Oracle 网络配置助手失败。在 Oracle 19c 安装期间
- coldfusion - 有没有办法将 PDF 嵌入到 CFMAIL 中?
- javascript - 在 JavaScript 中过滤和减少数组