feiyu02
2024-08-15 196bb14112448857a885e32dc4149e308e00b01a
src/main/kotlin/cn/flightfeather/supervision/infrastructure/utils/FileUtil.kt
@@ -1,11 +1,19 @@
package cn.flightfeather.supervision.infrastructure.utils
import java.io.File
import java.io.FileOutputStream
import net.coobird.thumbnailator.Thumbnails
import net.coobird.thumbnailator.tasks.io.FileImageSource
import org.springframework.util.Base64Utils
import java.awt.Image
import java.awt.image.BufferedImage
import java.io.*
import java.util.*
import javax.imageio.ImageIO
class FileUtil {
    @Throws(Exception::class)
object FileUtil {
    private const val SCHEME_PNG = "data:image/png;base64,"
    @Throws(FileNotFoundException::class)
    fun uploadFile(file: ByteArray, filePath: String, fileName: String) {
        val targetFile = File(filePath)
        if (!targetFile.exists()) {
@@ -15,6 +23,17 @@
        out.write(file)
        out.flush()
        out.close()
    }
    fun deleteFile(path: String) {
        val targetFile = File(path)
        if (targetFile.exists()) {
            try {
                targetFile.delete()
            } catch (e: SecurityException) {
                e.printStackTrace()
            }
        }
    }
    /**
@@ -29,4 +48,22 @@
        }
        return ""
    }
    /**
     * 按照固定宽度压缩图片至base64形式
     */
    fun compressImage2(bytes: ByteArray, w: Int): String {
        val input = ByteArrayInputStream(bytes)
        val srcImg = ImageIO.read(input)
        val srcW = srcImg.width
        val scale = w.toFloat() / srcW
        val h = (srcImg.height * scale).toInt()
        val buffImg = BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB)
        buffImg.graphics.drawImage(srcImg.getScaledInstance(w, h, Image.SCALE_SMOOTH), 0, 0, null)
        val out = ByteArrayOutputStream()
        ImageIO.write(buffImg, "PNG", out)
        return SCHEME_PNG + Base64.getEncoder().encodeToString(out.toByteArray())
    }
}