在 Kotlin 中解析 webp 文件 header 以获取其高度和宽度,但得到意想不到的结果

Parsing webp file header in Kotlin to get its height and width, but getting unexpected results

我正在尝试根据扩展文件格式 WebP Container Specification 读取 WebP 图片 header。

fun get24bit(data: ByteArray, index: Int): Int {
    return ((data[0 + index].toInt()) or (data[1 + index].toInt() shl 8) or (data[2 + index].toInt() shl 16))
}

fun get32bit(data: ByteArray, index: Int): Int {
    return get24bit(data, index) or (data[3 + index].toInt() shl 24)
}

// data -> File(fileName).readBytes() for testing purpose
fun webpExtract(data: ByteArray) {
    println(String(data.copyOfRange(0, 4)))
    println("Size: ${get32bit(data, 4)}")
    println(String(data.copyOfRange(8, 12)))
    println(String(data.copyOfRange(12, 16)))
    // 16, 17, 18, 19 reserved

    val width = 1 + get24bit(data, 20)
    val height = 1 + get24bit(data, 23)

    println("Width: $width, Height: $height")
}

输出为:

RIFF
Size: -52
WEBP
VP8X
Width: 17, Height: 32513

String 输出没问题,但 Size 变负,Width 和 Heights 错误,即它们应该分别为 128 和 128(对于我使用的测试图像)。

代码有问题吗?我无法弄清楚问题是什么。

我还验证了实际的 C++ 实现 here in github。我的代码进行了相同的位移,但结果不正确。据我所知,左移与无符号和有符号右移没有任何关系吗?

不知道 Spec 是不完整还是什么,我记录了字节值并以某种方式找到了一个模式。并且发现维度在24-26和27-29索引处。

val width = 1 + (get24bit(data, 24))
val height = 1 + (get24bit(data, 27))

这很管用!希望在文档未更新的情况下注意这一点会有所帮助。