2014-08-30 59 views
1

我在學習並嘗試解析BMP文件,但是如何將寬度/高度數據轉換爲正確的數字?我將字節轉換爲十進制數字,但它們以奇怪的格式出現。讀取24位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) 
+0

它們既在ReadFile函數聲明,字節19-22和23-26(或90 01 00 00和03 00 00 00) – 2014-08-30 16:58:45

回答

2
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 
+0

謝謝!這是完美的 – 2014-08-30 16:54:48