图片的保存
mPath = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString() + "/"
btn_save.setOnClickListener {
val bitmap = ll_info.drawingCache
val file_path = "$mPath${DateUtil.nowDateTime}.png"
FileUtil.saveImage(file_path, bitmap)
}
override fun onStart() {
super.onStart()
ll_info.isDrawingCacheEnabled = true
}
override fun onStop() {
super.onStop()
ll_info.isDrawingCacheEnabled = false
}
object FileUtil {
fun saveImage(path: String, bitmap: Bitmap) {
try {
val file = File(path)
//outputStream获取文件的输出流对象
val fos: OutputStream = file.outputStream()
//压缩格式为JPEG图像,压缩质量为80%
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos)
fos.flush()
fos.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
图片的读取
- 方式一
//readBytes读取字节数组形式的文件内容
val bytes = File(file_path).readBytes()
//decodeByteArray从字节数组解析图片
val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
- 方式二
//inputStream获取文件的输入流对象
val fis = File(file_path).inputStream()
//decodeStream从输入流解析图片
val bitmap = BitmapFactory.decodeStream(fis)
fis.close()
- 方式三
//decodeFile从指定路径解析图片
val bitmap = BitmapFactory.decodeFile(file_path)
文件遍历
遍历某个文件下的所有图片文件
var fileNames: MutableList<String> = mutableListOf()
val fileTree: FileTreeWalk = File(mPath).walk()
fileTree.maxDepth(1) //需遍历的目录层级为1,即无需检查子目录
.filter { it.isFile } //只挑选文件,不处理文件夹
.filter { it.extension in listOf("png", "jpg") } //选择扩展名为png和jpg的图片文件
.forEach { fileNames.add(it.name) } //循环处理符合条件的文件