我正在尝试创建一个程序,该程序从Lua中的网络上抓取图像。一个小问题是图像有时没有扩展名或扩展名不正确。参见以下动画“ jpeg”:http : //i.imgur.com/Imvmy6C.jpg
因此,我创建了一个函数来检测图像的文件类型。非常简单,只需比较返回图像的前几个字符。Png文件以PNG开头,Gif以GIF开头,而JPG则带有奇怪的符号“ begin”。
因为图像不应该表示为字符串,所以有点hacky,但是效果很好。除了我实际运行代码的时间。
当我在命令行中输入代码时,它可以正常工作。但是,当我运行包含代码的文件时,它不起作用。很奇怪,它只对jpegs失败。它仍然可以正确识别PNG和GIF。
这是重现该错误所需的最少代码:
http = require "socket.http"
function detectImageType(image)
local imageType = "unknown"
if string.sub(image, 2, 2) == "╪" then imageType = "jpg" end
return imageType
end
image = http.request("http://i.imgur.com/T4xRtBh.jpg")
print(detectImageType(image))
将其复制并粘贴到命令行中将正确返回“ jpg”。将其作为文件运行将返回“未知”。
我正在通过Powershell在Windows 8.1上使用Lua for Windows软件包中的Lua 5.1.4。
编辑:
发现问题string.byte(“╪”)在命令行上返回216,作为文件运行时返回226。我不知道为什么,也许lua和powershell的编码不同?
此行解决了问题:
if string.byte(string.sub(image, 2, 2)) == 216 then imageType = "jpg" end
我认为这是因为在保存文件时,会将文件另存为其他编码,因此╪字符可能会转换为其他字符。将其转换为字节码更健壮:
http = require "socket.http"
function detectImageType(image)
local imageType = "unknown"
if string.byte(image, 2) == 216 then imageType = "jpg" end
return imageType
end
image = http.request("http://i.imgur.com/T4xRtBh.jpg")
print(detectImageType(image))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句