道路线索应急巡查系统服务后台
feiyu02
2025-04-22 41548e262362faf603a71e066e01bd4ef46619d2
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.flightfeather.grid.utils
 
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 deleteFile(filePath: String): Boolean {
        val file = File(filePath)
        if (file.isDirectory) return false
        return if (file.exists()) {
            file.delete()
        } else {
            true
        }
    }
 
    fun deleteDirectory(path: String): Boolean {
        val file = File(path)
        return deleteDirectory(file)
    }
 
    fun deleteDirectory(file: File): Boolean {
        file.listFiles()?.forEach { deleteDirectory(it) }
        return if (file.exists()) {
            file.delete()
        } else {
            true
        }
    }
 
    /**
     * 获取文件名
     */
    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())
    }
}