Finally I have text file IO working correctly. I will probably make a Git of it later but I will just paste in the code for now. It seems to be working perfectly and pretty fast now with changes. I was experimenting with JSON encoded tables and it worked great. Or long text files can be stored, or use it as a sort of code obfuscation, etc. Just paste it into a blank tab and voila.
--Codea File IO using images
--By Kyle Howard (Vega) 2012
--Change it, use it, distribute it, whatever
--Usage :
--myString = "blah blah blah"
--fileio:write(myString, "Documents:myFile")
--myLoadedString = fileio:read("Documents:myFile")
-- if myLoadedString ~= nil then print (myLoadedString) end
fileio = {}
function fileio:read(imgName)
img = readImage(imgName)
if img == nil then return nil end
local r,g,b
local dstr = ""
local tx = {}
for y=2, img.rawHeight-1,3 do
for x=2,img.rawWidth-1,3 do
r,g,b = img:rawGet(x,y)
if r ~= 0 then table.insert(tx, string.char(r)) end
if g ~= 0 then table.insert(tx, string.char(g)) end
if b ~= 0 then table.insert(tx, string.char(b)) end
end
end
dstr = table.concat(tx)
return dstr
end
function fileio:write(str, imgName)
if str == nil then return false end
local rem = string.len(str)
local len = rem
local lines = 3
local cols = 600
if ContentScaleFactor == 2 then cols = 300 end
while rem > 800 do
lines = lines + 3
rem = rem - 800
end
local img = image(cols,lines)
for x=1, img.rawWidth do
for y=1,img.rawHeight do
img:rawSet(x,y,0,0,0,0)
end
end
local p1, p2, p3
local col = 1
local row = 1
local i = 1
while i <= string.len(str) + 3 do
p1 = 0
p2 = 0
p3 = 0
p4 = 255
if len >= i then p1 = string.byte(str,i) end
if len >= i + 1 then p2 = string.byte(str,i+1) end
if len >= i + 2 then p3 = string.byte(str,i+2) end
img:rawSet(row,col,p1,p2,p3,p4)
img:rawSet(row+1,col,p1,p2,p3,p4)
img:rawSet(row+2,col,p1,p2,p3,p4)
img:rawSet(row,col+1,p1,p2,p3,p4)
img:rawSet(row+1,col+1,p1,p2,p3,p4)
img:rawSet(row+2,col+1,p1,p2,p3,p4)
img:rawSet(row,col+2,p1,p2,p3,p4)
img:rawSet(row+1,col+2,p1,p2,p3,p4)
img:rawSet(row+2,col+2,p1,p2,p3,p4)
row = row + 3
if row > 598 then
row = 1
col = col + 3
end
i = i + 3
end
saveImage(imgName,img)
return true
end
And although this usage is already in comments, here is how to use it:
function setup()
myString = "blah blah blah"
fileio:write(myString, "Documents:myFile")
myLoadedString = fileio:read("Documents:myFile")
if myLoadedString ~= nil then print (myLoadedString) end
end
function draw()
background(40, 40, 50)
end
By the way, for those who haven’t been following, this saves text into images. So don’t use a name for your text file that you are already using for an image file or it will overwrite it.
Let me know if you encounter a bug. Thanks.