读取24位BMP宽度/高度



我正在学习并尝试解析BMP文件,但如何将宽度/高度数据转换为正确的数字?我正在把字节转换成十进制数字,但它们的格式很奇怪。

例如,宽度为3的图像显示为3 0 0 0,但宽度为400的图像显示出144 1 0 0

    local HexPaste = [[
    424d 480e 0000 0000 0000 3600 0000 2800
0000 9001 0000 0300 0000 0100 1800 0000
0000 120e 0000 120b 0000 120b 0000 0000
0000 0000 0000 3333 3333 3333 3333 3333
3333 3333 3333 3333 3333
]] --took out a bunch of pixel data which doesn't matter yet
function Compress(Hex)
    local returnString = {}
    for s in string.gmatch(Hex,'%x') do
        table.insert(returnString,#returnString+1,s)
    end
    returnString = table.concat(returnString,'')
    return returnString
end
function Read(Hex,Type,ByteA,ByteB)
    local STable = {}
    for s = ByteA,ByteB do
        if Type == 'Text' then
            table.insert(STable,#STable+1,string.char(tonumber(string.sub(Hex,(s*2)-1,s*2),16)))
        elseif Type == 'Deci' then
            table.insert(STable,#STable+1,tonumber(string.sub(Hex,(s*2)-1,s*2),16))
        end
    end
    return table.concat(STable,'')
end
function ReadFile(Hex)
    Hex = Compress(Hex)
    if Read(Hex,'Text',1,2) == 'BM' then
        local Width = Read(Hex,'Deci',19,22)
        local Height = Read(Hex,'Deci',23,26)
        print('File is '..Width..'x'..Height)
    else
        error('Incorrect File Type')
    end
end
ReadFile(HexPaste)
function Compress(Hex)
   return (Hex:gsub('%X',''))
end
function Read(Hex,Type,ByteA,ByteB)
   Hex = Hex:sub(2*ByteA-1,2*ByteB)
   if Type == 'Text' then
      return (Hex:gsub('..',function(h)return h.char(tonumber(h,16))end))
   elseif Type == 'Deci' then
      local v = 0
      Hex:reverse():gsub('(.)(.)',function(b,a)v=v*256+tonumber(a..b,16)end)
      return v
   end
end

最新更新