Kotlin 30. Kotlin 如何保存(图片)文件到本地

Kotlin 如何保存(图片)文件到本地

这里介绍我们如何将一张图片保存到指定的路径下。

比如,我们有一个 Bitmap 格式的照片,我们先需要输入这张照片需要保存的位置,比如我们这边保存照片在 Documents 文件夹下:

val extDir: File = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)

接下来,我们需要命名需保存的照片名字,并和上面的文件夹路径连在一起:

val fileName = "test.png"
val fullFilename = File(extDir, fileName)

最后就是保存:

try {
    
    
    val fOut = FileOutputStream(fullFilename)
    imageBitmap?.compress(Bitmap.CompressFormat.PNG, 85, fOut);
    fOut.flush()
    fOut.close()
    Log.i("ImageSave", "Image saved.")
} catch (e: Exception) {
    
    
    Log.i("ImageSave", "Failed to save image.")
}

猜你喜欢

转载自blog.csdn.net/zyctimes/article/details/129051480