首页 > 移动平台 > 详细

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

时间:2020-10-07 22:36:51      阅读:46      评论:0      收藏:0      [点我收藏+]
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://stackoverflow.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

原文:https://www.cnblogs.com/hangj/p/13779380.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!