package cn.flightfeather.supervision.infrastructure.utils
|
|
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.ByteArrayInputStream
|
import java.io.ByteArrayOutputStream
|
import java.io.File
|
import java.io.FileOutputStream
|
import java.util.*
|
import javax.imageio.ImageIO
|
|
|
object FileUtil {
|
private const val SCHEME_PNG = "data:image/png;base64,"
|
|
@Throws(Exception::class)
|
fun uploadFile(file: ByteArray, filePath: String, fileName: String) {
|
val targetFile = File(filePath)
|
if (!targetFile.exists()) {
|
targetFile.mkdirs()
|
}
|
val out = FileOutputStream(filePath + fileName)
|
out.write(file)
|
out.flush()
|
out.close()
|
}
|
|
/**
|
* 获取文件名
|
*/
|
fun getFileName(path: String?): String {
|
if (!path.isNullOrEmpty()) {
|
val dot = path!!.lastIndexOf('/')
|
if (dot > -1 && dot < path.length - 1) {
|
return path.substring(dot + 1)
|
}
|
}
|
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())
|
}
|
}
|