package com.yidian.shenghuoquan.newscontent.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.view.View
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream

/**
 * author: yinjiacheng
 * date: 5/30/21 2:02 PM
 * description: Bitmap相关操作
 */
object BitmapUtil {

  /**
   * 从Uri生成Bitmap
   * @param container bitmap容器
   */
  fun generateBitmapFromUri(context: Context?, uri: Uri?, container: View): Bitmap? {
    if (uri == null) return null
    val parcelFileDescriptor = context?.contentResolver?.openFileDescriptor(uri, "r")
    val options = BitmapFactory.Options()
    options.inJustDecodeBounds = true
    BitmapFactory.decodeFileDescriptor(parcelFileDescriptor?.fileDescriptor, null, options)
    // 尺寸压缩
    val sourceWidth = options.outWidth
    val sourceHeight = options.outHeight
    var inSampleSize = 1
    if (sourceWidth > container.width || sourceHeight > container.height) {
      val halfWidth = sourceWidth / 2
      val halfHeight = sourceHeight / 2
      // 压缩后的尺寸与所需的尺寸进行比较
      while (halfWidth / inSampleSize >= container.width && halfHeight / inSampleSize >= container.height) {
        inSampleSize *= 2
      }
    }
    options.inSampleSize = inSampleSize
    options.inJustDecodeBounds = false
    val bitmap =
      BitmapFactory.decodeFileDescriptor(parcelFileDescriptor?.fileDescriptor, null, options)
    parcelFileDescriptor?.close()
    return bitmap
  }

  /**
   * 从Bitmap生成File
   * @param quality 压缩质量
   * @param destPath 目标文件全路径
   */
  fun generateFileFromBitmap(bitmap: Bitmap?, quality: Int, destPath: String) {
    val file = File(destPath)
    if (file.exists()) file.delete()
    if (file.parentFile?.exists() == false) file.parentFile?.mkdirs()
    file.createNewFile()
    val outputStream = FileOutputStream(destPath)
    bitmap?.compress(Bitmap.CompressFormat.JPEG, quality, outputStream)
    outputStream.close()
  }

  /**
   * 图片压缩
   * @param path 将要压缩的图片圈路径，同时也是压缩完成后的图片 即覆盖原图片
   * @param quality 压缩质量
   */
  fun compressImage(path: String, quality: Int) {
    if (!File(path).exists()) throw FileNotFoundException("compress file not exist!")
    BitmapFactory.decodeFile(path)
      .compress(Bitmap.CompressFormat.JPEG, quality, FileOutputStream(path))
  }

}
