According to the Wikipedia page, the width of a .bmp image is stored in the header of the file, in bytes 0x12 through 0x15. For example, in an image that is 256x256, bytes 0x12 through 0x15 would look like this; Ruby converts each byte to an integer:
file = File.open("red_bmp.bmp", "r")
bytes = file.bytes.to_a
bytes[0x12..0x15]
#=> [0, 1, 0, 0]
Run Code Online (Sandbox Code Playgroud)
为了将其转换为little-endian格式,我最好的解决方案是将每个十进制值转换为十六进制字符串,反转数组,连接元素,并将生成的十六进制字符串转换回整数.
width = bytes[0x12..0x15].map {|x| x.to_s(16).rjust(2, "0")}.reverse.join.to_i(16)
#=> 256
Run Code Online (Sandbox Code Playgroud)
x.to_s(16).rjust(2, "0"))?Ruby中的字节争论通常涉及String#unpack和Array#pack; 在您的情况下,您想要将一些字节解压缩到本机Ruby值,因此您需要String#unpack并且您希望使用以下V格式:
V | Integer | 32-bit unsigned, VAX (little-endian) byte order
Run Code Online (Sandbox Code Playgroud)
我会做这样的事情:
# The "b for binary" is important since you just want to deal with bytes
# and any encoding will get in the way.
fp = open(whatever, 'rb')
# Seek to the desired offset.
fp.seek(0x12)
# Read in four bytes.
s = fp.read(4)
# Unpack the bytes and the array:
two_fifty_six = s.unpack('V').first
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4383 次 |
| 最近记录: |