package com.yidian.bcommon.utils

import android.content.Context
import android.graphics.Bitmap
import id.zelory.compressor.Compressor
import id.zelory.compressor.constraint.destination
import id.zelory.compressor.constraint.format
import id.zelory.compressor.constraint.quality
import id.zelory.compressor.constraint.resolution
import kotlinx.coroutines.Dispatchers
import java.io.File

/**
 * author: yinjiacheng
 * date: 7/15/21 10:55 PM
 * description: 图片压缩工具
 * https://github.com/zetbaitsu/Compressor
 */
object ImageCompressUtils {

  /**
   * 图片压缩
   * @param srcFile 源文件
   * @param destFile 目标文件
   * @param destWidth 目标宽度
   * @param destHeight 目标高度
   * @param quality 压缩质量
   * @param format 压缩格式
   * @param syncOrAsync 同步or异步
   */
  suspend fun compress(
    context: Context,
    srcFile: File,
    destFile: File? = null,
    destWidth: Int? = null,
    destHeight: Int? = null,
    quality: Int? = null,
    format: Bitmap.CompressFormat = Bitmap.CompressFormat.JPEG,
    syncOrAsync: Boolean = false
  ): File {
    return Compressor.compress(context, srcFile, if (syncOrAsync) Dispatchers.Main else Dispatchers.IO) {
      destFile?.let { destination(it) }
      destWidth?.let { width -> destHeight?.let { height -> resolution(width, height) } }
      quality?.let { quality(it) }
      format(format)
    }
  }
}
