feiyu02
2022-10-21 f22c4b9230808fed4fec80c435eccb4c833349a0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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())
    }
}