根据InputStream判断是否JPEG/PNG/GIF

注意:如果报错 IOException: mark/reset not supported
BufferedInputStream()包裹一层
 

private fun getImageType(inputStream: InputStream): String {
        try {
            val header = ByteArray(8)
            //标记
            inputStream.mark(8)
            val bytesRead = inputStream.read(header)
            //还原
            inputStream.reset()
            if (bytesRead == 8) {
                if (isJPEG(header)) {
                    return "JPEG"
                } else if (isPNG(header)) {
                    return "PNG"
                } else if (isGIF(header)) {
                    return "GIF"
                }
            }
        }catch (e:IOException){
            e.printStackTrace()
            return "Unknown"
        }
        return "Unknown"
    }

    private fun isJPEG(header: ByteArray): Boolean {
        return header[0] == 0xFF.toByte() && header[1] == 0xD8.toByte()
    }

    private fun isPNG(header: ByteArray): Boolean {
        return header[0] == 0x89.toByte() && header[1] == 0x50.toByte() && header[2] == 0x4E.toByte() && header[3] == 0x47.toByte() && header[4] == 0x0D.toByte() && header[5] == 0x0A.toByte() && header[6] == 0x1A.toByte() && header[7] == 0x0A.toByte()
    }

    private fun isGIF(header: ByteArray): Boolean {
        return header[0] == 0x47.toByte() && header[1] == 0x49.toByte() && header[2] == 0x46.toByte() && header[3] == 0x38.toByte() &&
                (header[4] == 0x37.toByte() || header[4] == 0x39.toByte()) && header[5] == 0x61.toByte()
    }

你可能感兴趣的:(kotlin,Android)