package mtp.polymer.com.autowidget.expand

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Environment
import androidx.appcompat.app.AppCompatActivity
import java.io.File
import java.io.FileOutputStream

import java.io.IOException


/**
 * 保存图片到相册
 * @param context
 * @param bitmap
 */
fun AppCompatActivity.saveBitmapToGallery(context: Context, bitmap: Bitmap): Boolean {
    val storePath = Environment.getExternalStorageDirectory().absolutePath + File.separator + context.packageName
    val appDir = File(storePath)
    if (!appDir.exists()) {
        appDir.mkdir()
    }
    val fileName = System.currentTimeMillis().toString() + ".jpg"
    val file = File(appDir, fileName)
    try {
        val fos = FileOutputStream(file)
        //通过io流的方式来压缩保存图片
        val isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
        fos.flush()
        fos.close()

        //把文件插入到系统图库

        //保存图片后发送广播通知更新数据库
        val uri = Uri.fromFile(file)
        context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri))
        return isSuccess
    } catch (e: IOException) {
        e.printStackTrace()
    }
    return false
}