android bitmap保存为file文件,并更新到图库

第一步:

/**
     * 该方式原理主要是:View组件显示的内容可以通过cache机制保存为bitmap
     */
    fun createBitmapFromView(view: View): Bitmap? {
        var bitmap: Bitmap? = null
        //开启view缓存bitmap
        view.isDrawingCacheEnabled = true
        //设置view缓存Bitmap质量
        view.drawingCacheQuality = DRAWING_CACHE_QUALITY_HIGH
        //获取缓存的bitmap
        val cache = view.drawingCache
        if (cache != null && !cache.isRecycled) {
            bitmap = Bitmap.createBitmap(cache)
        }
        //销毁view缓存bitmap
        view.destroyDrawingCache()
        //关闭view缓存bitmap
        view.isDrawingCacheEnabled = false
        return bitmap
    }

第二步:

/**
     * 创建保存图片的文件
     */
     fun createImageFile(context: Context): File? {
        val imageName: String =
            SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        if (!storageDir!!.exists()) {
            storageDir.mkdir()
        }
        val tempFile = File.createTempFile(imageName, ".jpg", storageDir)
        return if (Environment.MEDIA_MOUNTED != EnvironmentCompat.getStorageState(tempFile)) {
            null
        } else tempFile
    }

第三步:

val bmp = PublicTools.tools.createBitmapFromView(llPostLay)
val file = PublicTools.tools.createImageFile(context)
if (file == null){
     Toast.makeText(context, "保存海报失败", Toast.LENGTH_SHORT).show()
      return
}
 try {
     val fos = FileOutputStream(file)
     bmp?.compress(Bitmap.CompressFormat.JPEG, 100, fos)
     fos.flush()
     fos.close()
  }catch (e:Exception){
     e.printStackTrace()
     Toast.makeText(context, "保存海报失败", Toast.LENGTH_SHORT).show()
 }
 // 其次把文件插入到系统图库
try {
     MediaStore.Images.Media.insertImage(context.contentResolver,file!!.absolutePath, file.name, null)
} catch (e: Exception) {
    e.printStackTrace()
    Toast.makeText(context, "保存海报失败", Toast.LENGTH_SHORT).show()
}
context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)))
Toast.makeText(context, "保存海报成功", Toast.LENGTH_SHORT).show()

你可能感兴趣的:(android bitmap保存为file文件,并更新到图库)