package com.base.scanqr.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream

object BitmapUtils {

    fun Context.saveBitmapToFile(bitmap: Bitmap, filePath: String): Boolean {
        val file = File(filePath)
        if (!file.exists()) file.createNewFile()
        return try {
            FileOutputStream(file).use { fos ->
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
                fos.flush()
            }
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    fun Context.uriToBitmap(uri: Uri): Bitmap? {
        return try {
            // 获取ContentResolver实例
            val contentResolver = contentResolver

            // 打开InputStream
            val inputStream: InputStream = contentResolver.openInputStream(uri) ?: return null

            // 使用BitmapFactory解码InputStream
            val bitmap: Bitmap = BitmapFactory.decodeStream(inputStream)

            // 关闭InputStream
            inputStream.close()

            bitmap
        } catch (e: IOException) {
            e.printStackTrace()
            null
        }
    }
}