在Kotlin中解析webp文件头以获取其高度和宽度,但得到了意外的结果 [英] Parsing webp file header in Kotlin to get its height and width, but getting unexpected results

查看:217
本文介绍了在Kotlin中解析webp文件头以获取其高度和宽度,但得到了意外的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 WebP容器,我正在尝试读取WebP图像标头扩展文件格式的规范.

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

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

The String outputs are alright, but the Size is getting negative and Width and Heights are wrong i.e. They should be 128 and 128 respectively (for the test image I've used).

代码中有什么问题吗?我无法找出问题所在.

Is there something wrong in the code? I am not able to figure out what's the problem.

我还验证了实际的C ++实现在github 中.我的代码执行相同的位移,但是结果不正确.据我所知,左移与无符号和有符号右有什么关系?

I've also verified the actual C++ implementation here in github. My code does the same bit shifting, but the results are not correct. As far as I know, left shifting does not has anything to do with unsigned and signed right?

推荐答案

不知道

Don't know the Spec was incomplete or something, I logged the byte values and found a pattern somehow. And found that the dimensions are at 24-26 and 27-29 indexes.

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

这可以解决问题!希望注意这一点是有益的,只要不更新文档即可.

This does the trick! Hopefully it is helpful to note this point as long as documentation is not updated.

这篇关于在Kotlin中解析webp文件头以获取其高度和宽度,但得到了意外的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆