android kotlin determine file type from bytes 根据文件内容识别文件类型,类似python的filetype

fun byteArrayOfInts(vararg ints: Int) = ByteArray(ints.size) { pos -> ints[pos].toByte() }

val sig2mime = HashMap<ByteArray, Pair<String, Int> > ().apply {
    this[byteArrayOfInts(0xff, 0xd8)] = Pair("image/jpeg", 0) // mime, offset
    this[byteArrayOfInts(0x42, 0x4d)] = Pair("image/bmp", 0)
    this[byteArrayOfInts(0x47, 0x49, 0x46, 0x38)] = Pair("image/gif", 0)
    this[byteArrayOfInts(0x89, 0x50, 0x4E, 0x47)] = Pair("image/png", 0)
    this[byteArrayOfInts(0x66, 0x74, 0x79, 0x70)] = Pair("video/mp4", 4)
    this[byteArrayOfInts(0x52, 0x49, 0x46, 0x46)] = Pair("video/avi", 0)
}

fun guess(bytes: ByteArray):String{
    for ((k,v) in sig2mime){
        var cs = bytes.copyOfRange(v.second, bytes.size).contentToString()
        cs = cs.substring(1, cs.length-1)

        var kcs = k.contentToString()
        kcs = kcs.substring(1, kcs.length-1)

        if (cs.startsWith(kcs))
            return v.first
    }

    return ""
}

参考链接:
https://*.com/a/29033128/1936057
https://www.garykessler.net/library/file_sigs.html
https://www.freeformatter.com/mime-types-list.html
https://filesignatures.net/index.php?page=all

android kotlin determine file type from bytes 根据文件内容识别文件类型,类似python的filetype

上一篇:django-django添加检查用户名和手机号数量接口


下一篇:2020年uniapp学习手记-基础篇,和我一起学uniapp